gpt4 book ai didi

c - Sigaction 和 SIGALRM

转载 作者:行者123 更新时间:2023-11-30 14:57:05 29 4
gpt4 key购买 nike

嗨,我正在尝试了解有关信号的更多信息,我编写了一个简单的代码,该代码应该只打印“再见”发送警报信号的所有内容。我正在使用 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");
}

最佳答案

sigaction 不能返回 null,因为它返回一个整数。我假设它返回-1。您没有正确初始化 sigaction 结构。它有很多字段,但您允许它们未定义。修复结构定义并重试。请参阅:

http://man7.org/linux/man-pages/man2/sigaction.2.html

关于c - Sigaction 和 SIGALRM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44147464/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com