Contributors

Monday, July 25, 2011

A code piece becomes a daemon!


Daemonize a process
A daemon is started either by the system itself or a user in a terminal or script. When it does start, the process is just like any other executable on the system. To make it truly autonomous, a child processmust be created where the actual code is executed. This is known as forking, and it uses the fork() function:
/* Include header */
#include < stdio.h >
#include < stdlib.h >

/* Include daemon properties with the running code */
static void daemonize(void)
{
    pid_t pid, sid;

    if ( getppid() == 1 ) return;

    pid = fork();
    if (pid < 0) {
        exit(1);
    }
    if (pid > 0) {
        exit(0);
    }
/* The fork() function returns either the process id (PID) of the child process (not equal to zero), or -1 on failure. If the process cannot fork a child, then the daemon should terminate right here.
If the PID returned from fork() did succeed, the parent process must exit gracefully. This may seem strange to anyone who hasn't seen it, but by forking, the child process continues the execution from here on out in the code. */
    umask(0);
/* In order to write to any files (including logs) created by the daemon, the file mode mask (umask) must be changed to ensure that they can be written to or read from properly */
    sid = setsid();
    if (sid < 0) {
        exit(1);
    }
/* The child process must get a unique SID from the kernel in order to operate. Otherwise, the child process becomes an orphan in the system. The pid_t type, declared in the previous section, is also used to create a new SID for the child process */
    if ((chdir("/")) < 0) {
        exit(0);
    }
 /* The current working directory should be changed to some place that is guaranteed to always be there. Since many Linux distributions do not completely follow the Linux Filesystem Hierarchy standard, the only directory that is guaranteed to be there is the root (/). We can do this using the chdir() function */
    freopen("/dev/null", "r", stdin);
    freopen("/dev/null", "w", stdout);
    freopen("/dev/null", "w", stderr);
/* Close the file descriptors as the daemon need not use the terminal */
}

/* Our running code */ 
int main( int argc, char *argv[]) {
/* Call the daemonize function to make this running code as daemon */
                daemonize();
                while (1) {
/* Endless looping to do our stuff autonomously */
                                sleep(10);
                }
    return 0;
}

Compile:  cc –o

No comments:

Post a Comment