通过信号SIGQUIT唤醒睡眠守护进程

问题描述 投票:0回答:1

我的C(Linux)编写的守护程序有问题。我的程序首先处于睡眠过程中,然后在收到信号后醒来。我应该在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);
}
c linux signals
1个回答
0
投票

我应该在myhandler写什么?

空信号处理函数很好。它打断了sleep。见man signal(7)

如果被处理程序中断,sleep函数也永远不会重新启动,但会给出成功返回:剩余的休眠秒数。

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

Ef。:

#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
© www.soinside.com 2019 - 2024. All rights reserved.