[LCP]Daemons and syscalls

Roberto Diaz rdiazmartin at vivaldi.dhis.org
Thu Sep 13 05:55:05 UTC 2001


> > a) How do you create daemons?
> As an idea they are pretty easy:
> 	fork()
> 	if error
> 		print error and quit
> 	if parent
> 		exit
> 	if child
> 		close stdin/stdout/stderr

Dont forget setsid(2)... you can use this:

void
daemonize ()
{
  pid_t pid;
  create_log (); 
  pid = fork ();
  if (pid < 0) fatal ("daemonize");
  if (pid > 0)  exit (EXIT_SUCCESS);
  // child
  pid = setsid ();
  if (pid < 0) log ("setsid", 0);
  pid = fork ();
  if (pid < 0) log ("second fork", LOG_EMERG);
  if (pid > 0) exit (EXIT_SUCCESS);
  if (chdir(server_root) < 0) log ("chdir", LOG_EMERG);
  
  umask (066); // rw-------
  close (0);
  close (1);
  close (2);
}

---
Roberto Diaz <rdiazmartin at vivaldi.dhis.org>
..For a Brave GNU World..    
                                        Concerto Grosso Op. 3/8 A minor
                        Antonio Vivaldi (so... do you need beautiful words?)
                                                                      -----




More information about the linuxCprogramming mailing list