在linux中创建一个守护进程

时间:2014-03-09 10:00:37

标签: 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()的函数;在子进程内从子进程中的客户端接收数据,我在父进程中没有做任何事情(只是我要退出)。稍后调用守护进程在后台运行我的计时器任务

我的问题:如果我这样做,那么我的计时器任务将继续在后台运行,并且创建套接字将继续接收来自客户端的数据

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

如果您的应用是以下类型之一:

{
  ".sh": "bash",
  ".py": "python",
  ".rb": "ruby",
  ".coffee" : "coffee",
  ".php": "php",
  ".pl" : "perl",
  ".js" : "node"
}

你想使用npm&lt; pm2包。

只需运行pm2 start即可对您的应用进行守护。

此外,虽然您的应用通常在1核心上运行,但是使用pm2,您可以非常轻松地在所有核心上运行您的应用,并且它将在核心之间实现负载平衡。如果这听起来太异国情调,那么它也很容易不加载平衡!

这就是你要做的:

npm install -g pm2

pm2 start app.js -i 0 --name "api" # load balance app on all cores

pm2 start app.js --name "api" # run on 1 core, like apps typically do

然后:

pm2 startup (creates a pm2 systemd or equivalent service)

pm2 save (remembers the apps pm2 is running and starts them on reboot)

完成!

相关问题