我的目标是制作一个每秒发出一次的警报,以便当它由 sigaction 处理时它会打印时间,因此每秒都会打印新时间。我在这段代码中间有一个循环,它计数一个随机数,但我把它拿出来使这段代码更加简洁并且更易于查看,因为我相信问题在于我如何使用 sigaction,因为它打印了多个一秒钟的时间,但我这一秒钟只需要一行输出。
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
void alarmPrint(int signum);
time_t curtime;
int main(){
printf("Enter ^C to end the program:\n");
struct sigaction sig;
sig.sa_handler = alarmPrint;
int count;
int final;
time(&curtime);
srandom(curtime);
while(1){
time(&curtime);
alarm(1);
printf("\n");
if(sigaction(SIGALRM, &sig, 0) == -1){
printf("Error\n");
}
}
return 0;
}
void alarmPrint(int signum){
printf("current time is %s\n", ctime(&curtime));
}
最佳答案
正如其他人指出的那样。
您应该将 sigaction 移到循环和警报之外。
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
void alarmPrint(int signum);
int main(){
int count;
int final;
printf("Enter ^C to end the program:\n");
signal(SIGALRM, alarmPrint);
alarm(1);
while(1) {
/* do other stuff here */
}
return 0;
}
void alarmPrint(int signum){
time_t curtime;
time(&curtime);
printf("current time is %s", ctime(&curtime));
alarm(1);
}
您还需要在 alarmPrint()
函数中重置闹钟,以便它会在一秒钟内响起。
最后,ctime()
已经包含了一个新行,因此在打印时间时不需要新行。
关于c - sigaction 捕获 SIGALRM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26723621/