【问题标题】:Creating a daemon with stop, start functionality in C在 C 中创建具有停止、启动功能的守护程序
【发布时间】:2010-09-16 12:14:02
【问题描述】:

如何在这个守护进程代码中添加守护进程停止、启动和报告功能?

#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>

int main(void) {

        /* 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);
        }

        /* Close out the standard file descriptors */
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        close(STDERR_FILENO);

        /* Daemon-specific initialization goes here */

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

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

【问题讨论】:

    标签: c programming-languages daemon unix


    【解决方案1】:
    1. 将守护进程的 pid 写入/var/run/mydaemonname.pid,以便以后轻松查找 pid。
    2. 为 SIGUSR1 和 SIGUSR2 设置信号处理程序。
    3. 获得 SIGUSR1 后,切换停止标志。
    4. 获得 SIGUSR2 后,设置报告标志。
    5. 在您的 while 循环中,检查每个标志。
    6. 如果设置了停止标志,则停止直到它被清除。
    7. 如果设置了报告标志,请清除该标志并进行报告。

    停止/启动有一些复杂性,但如果我正确理解了这个问题,这应该会让你走上正轨。

    编辑:添加了 Dummy00001 在下方评论中建议的 pid 文件。

    【讨论】:

    • 您可能还会提到创建一个 pid 文件 - 这样 pid 就无需猜测就可以知道。
    【解决方案2】:

    首先,您可能不必自己做这么多的分叉和管家工作:http://linux.die.net/man/3/daemon

    接下来,请记住,您的守护程序与世界的接口可能是通过您也编写的某种 shell 脚本,该脚本位于 /etc/init.d 或任何其他发行版定义的位置。

    因此,对于上述答案,您的 shell 脚本会将这些信号发送到进程的 pid。不过可能有更好的方法。像上面这样的信号是一个单向过程,您的控制脚本必须跳过容易出现竞争条件和脆弱的箍,以确认守护程序是否成功停止或重新启动。我会在 /etc/init.d 中查找优先级和示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-10
      • 1970-01-01
      • 2011-09-20
      • 2012-09-05
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多