在 linux 中创建一个守护进程

标签 c linux process timer daemon

#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) {             //child process
                CreateSocket();    //this function will recieve the data from the client
        }
        else
        {
         exit(EXIT_SUCCESS);   //exit the parent process
        }

        /* 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 ... */

           Timer();   // this will create a timer and call the task for every 2ms, 10ms
        }
   exit(EXIT_SUCCESS);
}

我的任务是通过套接字从客户端接收数据并在后台运行计时器。所以我创建了一个父进程和子进程,后来又创建了守护进程在后台运行。我调用了名为 CreateSocket() 的函数;在子进程中从子进程中的客户端接收数据,而我在父进程中没有做任何事情(只是我正在退出)。稍后调用守护进程在后台运行我的定时器任务

我的问题:如果我像上面那样做,那么我的定时器任务将继续在后台运行,创建套接字将继续从客户端接收数据

最佳答案

守护进程的最简单方法是使用 daemon(3)程序开头附近的库函数(内部基于 forksetsid...)(例如,在创建任何线程之前)。

关于在 linux 中创建一个守护进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22280848/

相关文章:

c - 我的服务器在c中不接受为什么?

java - 如何在类路径中包含一个 jar 文件并在 linux 中运行另一个 jar

python - 使用参数从 subprocess.call 调用应用程序

ruby - 如何在 Ruby 中打开进程的 STDIN?

c - 仅当变量之和等于 1 时才执行代码

c - 有没有办法测试我是否在信号处理程序中?

java - 使用 JNA-Ptrace 在 Linux 中获取有关外部进程的信息?

c# - .NET 进程间通信的最佳选择是什么?

c - struct_ 前缀与无前缀

c - 警告 : assignment from incompatible pointer type