Tuesday, April 24, 2012

C - Function to become a deamon

When you run a program normally it is attached to the terminal you are running the command in and tied to the session that is logged in.    When you want to give your program the ability to keep running even when the user closes a terminal, or logs out, especially for system tasks, then you need to make your program become a deamon process.

Typically this process is sort of a pain, but I went out and looked up all the things you need to do to successfully become a deamon and put it all in this one function. 

This way you can just copy and paste this into your own programs and become a deamon whenever you want. 

I don't have any copyright on this function, it is an amalgamation of standard techniques from many sources. 


/*
 * Do whatever it takes to become a deamon process
 */

 void become_deamon ( struct conf_t *conf ) {

     int i, max_files, fd;

    /* following line could be adjusted to output info for your particular program */
    /* notify(__FILE__, __LINE__, "Beginning become_deamon"); */

     /* close all open file descriptors */
     max_files=getdtablesize();
     for (i = 0; i < max_files; i++)
        close(i);

     /* change to log directory */
     /* chdir(conf.defaults.logdir); */
     chdir("/");

     /* reset the file access creation mask */
     umask(0);

     /* ignore terminal i/o signals */
     #ifdef SIGTTOU
        signal(SIGTTOU, SIG_IGN);
     #endif
     #ifdef SIGTTIN
        signal(SIGTTIN, SIG_IGN);
     #endif
     #ifdef SIGTSTP
        signal(SIGTSTP, SIG_IGN);
     #endif

     /* run in the background */
     /* disassociate from process group */
     setpgrp();
     /* disassociate from control terminal */
     if ( fork() != 0)
        exit(0); /* parent process */
     setpgrp();
     if ( fork() != 0)
        exit(0);  /* parent process */
     if ( (fd = open("/dev/tty", O_RDWR)) >= 0) {
        ioctl(fd, TIOCNOTTY, (char *) 0); /* lose control tty */
        close(fd);
     }
     /* don't reacquire a control terminal */
    }  /* end become_deamon */

No comments:

Post a Comment