我正在尝试使用POSIX sigaction函数学习信号。
我要做的是提示用户输入。提示后,设置5秒钟警报。如果用户在警报到期之前没有输入内容,则会重新提示用户。如果用户确实输入了某些内容,则会取消警报并回显输入。如果在第三次重新提示后没有输入,程序将退出。
以下是我到目前为止的情况。这样做是在第一次显示提示后,当没有输入任何输入时,它会以“报警信号”消息退出。
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <signal.h>
volatile sig_atomic_t count = 0;
void sighandler(int signo)
{
++count;
}
int main(void)
{
char buf[10];
struct sigaction act;
act.sa_handler = sighandler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
if(sigaction(SIGINT, &act, 0) == -1)
{
perror("sigaction");
}
while(count < 3)
{
printf("Input please: ");
alarm(5);
if(fgets(buf, 10, stdin))
{
alarm(0);
printf("%s", buf);
}
}
return 0;
}
答案 0 :(得分:3)
您正在为SIGINT
而不是SIGALRM
注册处理程序。因此,当警报到达时,它没有被捕获,根据默认处置,该过程终止。
作为旁注,您也可以使用select
。