我在编写一小段代码时遇到了困难:
act_therm.sa_handler=handler_therm;
sigaction(SIGUSR1,&act_thermom,NULL);
while(1){
raise(SIGUSR1);
sleep(1);
}
代码编译完美,但函数 handler_term 仅启动一次。信号的行为似乎在首次引发后重置为默认值。
最佳答案
我终于在书中找到了完整的答案:
通过像这样声明结构:
struct sigaction act_therm;
act_therm.sa_handler=handler_therm;
标志 SA_RESETHAND (默认情况下)附加到结构。每次调用 sigaction 时,它都会恢复信号的默认行为。
有两种方法可以解决这个问题:
- 不好的,每次使用 sigaction 调用信号时都会重新定义信号的行为
- 定义完整的结构(来自 man)并创建 sa_flags 以便 SA_RESETHAND 不会被调用:
struct sigaction { void (*sa_handler) (int); void (*sa_sigaction) (int, siginfo_t *, void *); sigset_t sa_mask; int sa_flags; void (*sa_restorer) (void); };
关于c - while 循环中的 raise(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36363268/