How to daemonize the process



/******************************************************************************
 * Function Name : daemonizeserver
 * Parameters    : NULL
 * Description   : This function daemonizes the smash server
 * Return Value  : NULL
******************************************************************************/
/*
Steps:
------
1. fork() a new process and get the new pid.
2. If forking of the new processes returned error return failure
3. Call setsid() to run the program in the new session. If any error is
   is occured return error
4. Change the current working directory. This prevents the current
   directory from being locked; hence not being able to remove it.
5. If creating a new child processes is success then remove the parent
   processes and return success
*/

static int daemonizeserver()
{
    int retVal = SM_FAILURE;
    pid_t pid = 0, sid = 0;

    // fork off the parent process
    pid = fork();
    if (pid < 0) {
        // some error has occured so returning failure
        TCRIT("daemonizeserver - Unable to fork a new processes");
        goto end;
    }

    if (pid == 0) {
        // create a new SID for the child process
        sid = setsid();
        if (sid < 0) {
            // some error occured so returning failure
            TCRIT("daemonizeserver - Unable to create a new SID");
            goto end;
        }

        // Change the current working directory.
        if ((chdir("/")) < 0) {
            // some error occured so returning failure
            TCRIT("daemonizeserver - Unable to change the working directory");
            goto end;
        }
        retVal = SM_SUCCESS;
    }

    // got a pid so exit the parent
    if (pid > 0) {
        exit(EXIT_SUCCESS);
    }

end:
    return retVal;
}


--

Comments

Popular Posts