gpt4 book ai didi

c - sighandler 中的第二个信号调用 - 为什么?

转载 作者:行者123 更新时间:2023-12-02 04:57:32 25 4
gpt4 key购买 nike

最近我发现一些代码使用了signal :

  286 static void sighandler( int signum )
287 {
288 alarmed = 1;
289 signal( signum, sighandler );
290 }
291
292 void set_alarm( int seconds )
293 {
294 alarmed = 0;
295 signal( SIGALRM, sighandler );
296 alarm( seconds );
297 }

我很难弄清楚为什么我需要调用 signal 2次,特别是,为什么我需要打电话signalsighandler ?我知道上面的代码是做什么的,但不明白为什么我需要调用 signal 2 次。

最佳答案

Handling Signals

The call to signal establishes signal handling for only one occurrence of a signal. Before the signal-handling function is called, the library resets the signal so that the default action is performed if the same signal occurs again. Resetting signal handling helps to prevent an infinite loop if, for example, an action performed in the signal handler raises the same signal again. If you want your handler to be used for a signal each time it occurs, you must call signal within the handler to reinstate it. You should be cautious in reinstating signal handling. For example, if you continually reinstate SIGINT handling, you may lose the ability to interrupt and terminate your program.

signal() 函数仅定义对下一个接收信号的处理,之后恢复默认处理。因此,如果程序需要使用非默认处理程序继续处理信号,则信号处理程序有必要调用 signal()

关于c - sighandler 中的第二个信号调用 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17728050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com