我正在嘗試使用POSIX sigaction函數學習信號。使用sigaction學習POSIX信號
我想要做的是提示用戶輸入。提示後,設置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;
}
您正在捕獲'SIGINT',但警報使用'SIGALRM'。 – user786653
謝謝你,user786653。 – user695752