我正在编写一个程序,其中 SIGINT 信号在第一次发送时进行处理,但之后设置为默认值。例如,我有这个:
static volatile int stop_terminating = 1;
void handler(int dummy) {
stop_terminating = 0;
}
int main(){
signal(SIGINT, handler);
char input[256];
while(1){
if(stop_terminating == 0){
// reset the action of the signal to default
signal(SIGINT, SIG_DFL);
printf("Message sent.\n");
// increment counter so it doesn't enter this condition again
stop_terminating++;
}
printf("User input:\n");
fgets(input, sizeof(input), stdin);
// In this stage, I wanna press CTRL+C and print a message, stopping the fgets
// but what happens is: I press CTRL+C, the signal is catched, but fgets
// is still asking for an input, and after I send something, the my message is printed
// because it looped through the while(1) again.
}
}
如何阻止 fgets 请求输入并打印消息,然后再次请求输入?
Linux 信号手册页说
信号处理程序中断系统调用和库函数
如果在系统调用或库函数调用被阻止时调用信号处理程序,则:
-
信号处理程序返回后,调用会自动重新开始;或者
-
调用失败并出现错误EINTR
.
这两种行为中的哪一种发生取决于接口以及信号处理程序是否是使用SA_RESTART
标志(参见sigaction
(2)).
您可以使用siginterrupt()
一起发挥作用signal()
,或使用sigaction()
代替signal()
用于注册您的信号处理程序,以禁用重新启动read()
信号后的系统调用。
但请注意fgets()
从 C 库可能会调用read()
多次直到找到换行符,因此您可能还需要切换到使用较低级别的函数而不是stdio.h
APIs.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)