Featured Post

Trie implementation in C

Creating a Daemon Process in Unix/Linux

This is a simple implementation of daemonizing a process.
A Daemon process is one which runs continously in the background and it can't be killed.

//process.c 

/*Compile this as 

  gcc -o process process.c 

*/

#include <stdio.h>

int main()
{
  int n = 0 ;

  while(1)
  {
    n++;
    printf("%d",n);
    sleep(1000000);
  }
}


//daemon.c

/* Run this as 
   gcc daemon.c
   ./a.out process
*/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <syslog.h>
#include <fcntl.h>
#include <sys/resource.h>

void daemonize(const char *cmd)
{
    int                 i, fd0, fd1, fd2;
    pid_t               pid;
    struct rlimit       rl;
    struct sigaction    sa;
    umask(0); //Set file creation mask to zero

    //Get maximum number of file descriptors.
    if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
    {    
      printf("%s: can't get file limit", cmd);
      exit(0);
    }

    //Become a session leader
    if ((pid = fork()) < 0)
    {
      printf("%s: can't fork", cmd);
      exit(0);
    }
    else if (pid != 0) /* parent */
        exit(0);
    setsid();

    //Ensure future opens won't allocate controlling TTYs.
    sa.sa_handler = SIG_IGN;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGHUP, &sa, NULL) < 0)
    {
        printf("Can't ignore SIGHUP");
        exit(0);
    }
    if ((pid = fork()) < 0)
    {
        printf("%s: can't fork", cmd);
        exit(0);
    }
    else if (pid != 0) /* parent */
        exit(0);

    /*
     * Change the current working directory to the root so
     * we won't prevent file systems from being unmounted.
     */
    if (chdir("/") < 0)
    {
        printf("Can't change directory to /");
        exit(0);
    }

    //Close all open file descriptors.
    if (rl.rlim_max == RLIM_INFINITY)
        rl.rlim_max = 1024;
    for (i = 0; i < rl.rlim_max; i++)
        close(i);


    //Attach file descriptors 0, 1, and 2 to /dev/null.
    fd0 = open("/dev/null", O_RDWR);
    fd1 = dup(0);
    fd2 = dup(0);

    //Initialize the log file.
    openlog(cmd, LOG_CONS, LOG_DAEMON);
    if (fd0 != 0 || fd1 != 1 || fd2 != 2)
    {
        printf("unexpected file descriptors %d %d %d",fd0, fd1, fd2);
        exit(1);
    }
}

int main(int argc , char **argv)
{
  if(argc != 2)
  {
    printf("Usage : %s <process-name>",argv[0]);
    exit(0);
  }

  daemonize(argv[1]);
}

Comments