~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

February 26, 2010

Writing a Daemon in Linux

Here is the sample C code on how to create a Daemon and play around with the PIDs. I am also a starter; comment if there is anything wrong!!! Let me know if you have any questions..

#include
#include
#include
#include
#include
#include
#include
#include
#include

int main(void) {
      
    /* Our process ID and Session ID */
    pid_t pid, sid;
    int seconds=0;
      
    /* Fork off the parent process */
    printf("Creating Child Process:\n ");
    pid = fork();
    printf("fork completed: pid = %d\n ", pid);
    if (pid < 0) {
        exit(EXIT_FAILURE);
    }
    /* If we got a good PID, then
    *  we can exit the parent process. */
    if (pid > 0) {
        exit(EXIT_SUCCESS);
    }

    printf("Creating child process success\n ");
    /* Change the file mode mask */
    umask(0);
              
    /* Open any logs here */      
              
    /* Create a new SID for the child process */
    sid = setsid();
    printf("Set Session ID = %d\n", sid);
    if (sid < 0) {
        /* Log the failure */
        exit(EXIT_FAILURE);
    }
      

    printf("Session ID creation success, now changing dir\n");
      
    /* Change the current working directory */
    if ((chdir("/")) < 0) {
        /* Log the failure */
        exit(EXIT_FAILURE);
    }
     
    /* Daemon-specific initialization goes here */
      
    /* The Big Loop */
    printf("$$$Daemon Started running$$$ \n");
    while (1) {
        /* Do some task here ... */
        /* Insert your task HERE.... which need to run in this process */
        printf("Daemon running at second-%d !!!!\n", seconds++);
        sleep(1); /* wait 1 second(s) */

        /* Daemon will be running for 100seconds */
        if (seconds == 100){
            printf("Daemon terminating at %d seconds!!!!\n", seconds);
            /* Close out the standard file descriptors */
            close(STDIN_FILENO);
            close(STDOUT_FILENO);
            close(STDERR_FILENO);
            break;     
        }      
    }
    exit(EXIT_SUCCESS);
}

No comments:

Post a Comment

Search SwamiSathappan's Blog

Currency Converter

About Me