我正在玩C中的信号。我的主要功能基本上要求使用fgets(name, 30, stdin)
进行一些输入,然后坐在那里等待。我用alarm(3)
设置了一个闹钟,然后我重新分配了SIGALRM来调用函数myalarm
,该函数简单地调用system("say PAY ATTENTION")
。但是在闹铃响起后,fgets()
停止等待输入,我的主要fn继续。即使我将myalarm
更改为只设置了一些变量并且什么也不做,会发生这种情况。为什么alarm()会导致fgets()停止等待?
void myalarm(int sig) {
//system("say PAY ATTENTION");
int x = 0;
}
int catch_signal(int sig, void (*handler)(int)) { // when a signal comes in, "catch" it and "handle it" in the way you want
struct sigaction action; // create a new sigaction
action.sa_handler = handler; // set it's sa_handler attribute to the function specified in the header
sigemptyset(&action.sa_mask); // "turn all the signals in the sa_mask off?" "set the sa_mask to contian no signals, i.e. nothing is masked?"
action.sa_flags = 0; // not sure, looks like we aren't using any of the available flags, whatever they may be
return sigaction(sig, &action, NULL); // here is where you actually reassign- now when sig is received, it'll do what action tells it
}
int main() {
if(catch_signal(SIGINT, diediedie)== -1) {
fprintf(stderr, "Can't map the SIGINT handler");
exit(2);
}
if(catch_signal(SIGALRM, myalarm) == -1) {
fprintf(stderr, "Can't map the SIGALAM handler\n");
exit(2);
}
alarm(3);
char name[30];
printf("Enter your name: ");
fgets(name, 30, stdin);
printf("Hello, %s\n", name);
return 0;
}
为什么alarm()
使fgets()
停止等待输入?
编辑:为我的catch_signal
函数添加了代码,并且根据其中一个注释,使用sigaction
而不是signal
,但问题依然存在。
请参阅'man 7 signal',子标题为“通过信号处理程序中断系统调用和库函数” – Retr0id
我看到这一点:“如果对信号处理程序中断了以下某个接口的阻塞呼叫,如果使用SA_RESTART标志,则在信号处理程序返回后调用将自动重新启动;否则调用将失败,并显示错误EINTR ...“并且fgets()未被列为可重新启动的函数之一。我试图做的是不可能的? –
'fgets()'在引擎盖下使用'read'系统调用。顺便说一句,在我的系统上它不会中断(Arch Linux x86_64) – Retr0id