Search in shivacherukuri.tech@blogger.com

Tuesday, May 17, 2011

Daemon creation example

* Rules:                                              *

* 1. Call 'fork' and have parent 'exit'                           *

* 2. Call 'setsid' to create a new session                        *

* 3. Change cwd to /   -> Else if a daemon is from a mounted            *

*    (or somewhere...)    filesystem, then that cannot be unmounted     *

* 4. Set file-mode-creation mask to 0, close unneeded file descriptors  * ************************************************************************/

 

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <stdlib.h>

 

static int global;

 

int main(void)

{

      pid_t pid;

     

      if ( (pid = fork()) < 0 )

         return -1;

      else if ( pid != 0 )

            exit(0);

      setsid();   /* this makes it a session leader */

      chdir("/"); /* so that other file systems can be unmounted */

      umask(0);   /* The file mode creation mask could have been inherited

                     with restrictive permissions. E.g, if the daemon

                     expects files that it creates to have group-read

                     groud-write bits enabled, and a file mode creation

                     mask has turned them off, then it would be a

                     problem */

      close(0);

      close(1);

      close(2);

 

      while(1) {

            ++global;

 

        };  /* Just to show some processing.... */

      return 0;

}

No comments:

Post a Comment