【问题标题】:wake up sleeping daemon by signal SIGQUIT通过信号 SIGQUIT 唤醒休眠的守护进程
【发布时间】:2019-04-12 09:44:47
【问题描述】:

我用 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】:

    myhandler 应该写什么?

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

    如果被处理程序中断,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
    

    【讨论】:

    • 我不明白,所以你说这应该有效?我不需要改变任何东西?
    • @Krystek102 是的,为您添加了一个示例。
    猜你喜欢
    • 1970-01-01
    • 2014-08-02
    • 2021-04-10
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    相关资源
    最近更新 更多