gpt4 book ai didi

c - 通过信号 SIGQUIT 唤醒 sleep 守护进程

转载 作者:太空宇宙 更新时间:2023-11-04 11:52:24 24 4
gpt4 key购买 nike

我用 C (Linux) 编写的守护程序有问题。我的程序首先处于 sleep 过程中,然后应该在收到信号后醒来。我应该在 myhandler 中写什么?

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
#include <signal.h>

void myhandler(int signal)
{


}
int main(void) {
signal(SIGQUIT,myhandler);

/* Our process ID and Session ID */
pid_t pid, sid;

/* Fork off the parent process */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* If we got a good PID, then
we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}

/* Change the file mode mask */
umask(0);

/* Open any logs here */

/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}



/* Change the current working directory */
if ((chdir("/")) < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}



/* Daemon-specific initialization goes here */

/* The Big Loop */
while (1) {
/* Do some task here ... */

sleep(30); /* wait 30 seconds */
}
exit(EXIT_SUCCESS);
}

最佳答案

What I should write in myhandler?

空信号处理函数很好。它会中断 sleep 。参见 man signal(7) :

The sleep function is also never restarted if interrupted by a handler, but gives a success return: the number of seconds remaining to sleep.

但是,我建议不要禁用 SIGQUIT 的默认操作,即终止进程和转储核心。 SIGINT 可能是更好的选择。

例如:

#include <signal.h>
#include <unistd.h>
#include <stdio.h>

static void signal_handler(int) {}

int main() {
signal(SIGINT, signal_handler);
if(sleep(60))
printf("signal received\n");
}

输出:

$ ./test
^Csignal received

关于c - 通过信号 SIGQUIT 唤醒 sleep 守护进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55648844/

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