我正在尝试使用 C 语言中的信号。我的主函数基本上使用 fgets(name, 30, stdin)
请求一些输入,然后等待。我使用 alarm(3)
设置了一个闹钟,并重新分配了 SIGALRM 调用一个名为 myalarm
的函数,该函数只是调用 system("say PAY ATTENTION")
。但是在闹钟响起后,fgets()
停止等待输入,而我的主函数继续执行。即使我将 myalarm
更改为仅设置某个变量并不对其进行任何操作,这种情况仍会发生。
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
,子标题为“通过信号处理程序中断系统调用和库函数”的部分。 - Retr0idfgets()
在底层使用read
系统调用。顺便说一下,在我的系统上(Arch Linux x86_64),它不会被中断。 - Retr0idcatch_signal()
,但我猜测你使用的是signal()
而不是sigaction()
,这意味着由fgets()
调用的read()
没有被重新启动。使用sigaction()
来控制它。 - Jonathan Leffler