嗨,我正在努力学习更多关于信号的知识,我写了一个简单的代码,应该只需打印警报信号所发送的所有内容。我正在使用sigaction来设置这个。但是,我在错误检查中一直返回NULL,有人能告诉我我做错了什么吗?提前谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/time.h> /* for setitimer */
#include <unistd.h> /* for pause */
#include <signal.h> /* for signal */
#define INTERVAL 500 /* number of milliseconds to go off */
/* function prototype */
void DoStuff();
int main(int argc, char *argv[]) {
struct itimerval it_val; /* for setting itimer */
struct sigaction sa;
sa.sa_handler = &DoStuff;
/* Upon SIGALRM, call DoStuff().
* Set interval timer. We want frequency in ms,
* but the setitimer call needs seconds and useconds. */
if (sigaction(SIGALRM,&sa,NULL) < 0) { /*set the signal to be enabled if this action occurs*/
perror("Unable to catch SIGALRM");
exit(1);
}
it_val.it_interval = it_val.it_value;
it_val.it_value.tv_sec = INTERVAL/1000;
it_val.it_value.tv_usec = (INTERVAL*1000) % 1000000;
it_val.it_interval = it_val.it_value;
if (setitimer(ITIMER_REAL, &it_val, NULL) == -1) { /*set the timer to send the alarm command*/
perror("error calling setitimer()");
exit(1);
}
while(1)
{
pause();
}
}
void DoStuff() {
printf("bye\n");
}发布于 2017-05-24 02:52:16
sigaction不能返回null,因为它返回一个整数。我猜它还在-1。您没有正确地初始化sigaction结构。它有许多字段,但是您允许它们是未定义的。修复结构定义,然后重试。请参见:
http://man7.org/linux/man-pages/man2/sigaction.2.html
https://stackoverflow.com/questions/44147464
复制相似问题