how to make a process daemon

佐手、 提交于 2019-11-26 18:46:58

问题


I am trying to understand how can I make my program a daemon.So some things which I came across are In general, a program performs the following steps to become a daemon:

  1. Call fork( ).
  2. In the parent, call exit( ). This ensures that the original parent (the daemon's grandparent) is satisfied that its child terminated, that the daemon's parent is no longer running, and that the daemon is not a process group leader. This last point is a requirement for the successful completion of the next step.

  3. Call setsid( ), giving the daemon a new process group and session, both of which have it as leader. This also ensures that the process has no associated controlling terminal (as the process just created a new session, and will not assign one).

  4. Change the working directory to the root directory via chdir( ). This is done because the inherited working directory can be anywhere on the filesystem. Daemons tend to run for the duration of the system's uptime, and you don't want to keep some random directory open, and thus prevent an administrator from unmounting the filesystem containing that directory.

  5. Close all file descriptors.

  6. Open file descriptors 0, 1, and 2 (standard in, standard out, and standard error) and redirect them to /dev/null.
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/fs.h>

int main (void)
{
    pid_t pid;
    int i;

    /* create new process */
    pid = fork ( );  
    if (pid == -1)  
        return -1;  
    else if (pid != 0)  
        exit (EXIT_SUCCESS);  

    /* create new session and process group */  
    if (setsid ( ) == -1)  
        return -1;  

    /* set the working directory to the root directory */  
    if (chdir ("/") == -1)  
        return -1;  

    /* close all open files--NR_OPEN is overkill, but works */  
    for (i = 0; i < NR_OPEN; i++)  
        close (i);  

    /* redirect fd's 0,1,2 to /dev/null */  
    open ("/dev/null", O_RDWR);  
    /* stdin */  
    dup (0);  
    /* stdout */  
    dup (0);  
    /* stderror */  

    /* do its daemon thing... */  

    return 0;  
}

Can some one give me a link to existing source code of some program like Apache so that I can understand this process in more depth.


回答1:


If you are looking for a clean approach please consider using standard api- int daemon(int nochdir, int noclose);. Man page pretty simple and self explanatory. man page. A well tested api far outweigh our own implementation interms of portability and stability.




回答2:


In Linux, it can be easily done using:

int main(int argc, char* argv[])
{
    daemon(0,0);
    while(1)
    {
        sleep(10)
        /*do something*/
    }

    return 0;
}


来源:https://stackoverflow.com/questions/5384168/how-to-make-a-process-daemon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!