4

Launch a demon

  1. /*
  2.  * Creates a daemon process.
  3.  *
  4.  *   fork
  5.  *   setsid
  6.  *   chdir
  7.  */
  8.  
  9. #include <sys/types.h>
  10. #include <unistd.h>
  11. #include <signal.h>
  12. #include <fcntl.h>
  13.  
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <errno.h>
  17. #if defined( LINUX )
  18. #include <string.h>
  19. #endif
  20.  
  21. int main( int argc, char **argv ) {
  22.     int pid;
  23.     int i, fd;
  24.  
  25.     pid = fork();
  26.  
  27.     if ( pid == -1 ) { /* error */
  28.         fprintf( stderr, "%s\n", strerror( errno ) );
  29.         exit( 1 );
  30.     }
  31.  
  32.     if ( pid != 0 ) /* parent */
  33.         exit( 0 );
  34.  
  35.     /* child */
  36.     setsid();
  37.  
  38.     pid = fork();
  39.  
  40.     if ( pid == -1 ) { /* error */
  41.         fprintf( stderr, "%s\n", strerror( errno ) );
  42.         exit( 1 );
  43.     }
  44.  
  45.     if ( pid != 0 ) /* parent */
  46.         exit( 0 );
  47.  
  48.     /* child */
  49.     chdir( "/" );
  50.     umask( 0 ); /* or 027 */
  51.  
  52.     /* catch signals */
  53.     signal( SIGHUP, SIG_IGN );
  54.     signal( SIGINT, SIG_IGN );
  55.     signal( SIGTERM, SIG_IGN );
  56.  
  57.     /* close all descriptors */
  58.     for ( fd = getdtablesize(); i >= 0; --i )
  59.         close( fd );
  60.  
  61.     /* reopen standard io */
  62.     fd = open( "/dev/null", O_RDWR ); /* stdin */
  63.     fd = open( "/dev/console", O_WRONLY ); /* stdout */
  64.     fd = open( "/dev/null", O_WRONLY ); /* stderr */
  65.  
  66.     setbuf( stdout, 0 );
  67.  
  68.     fprintf( stdout, "kill %i\n", getpid() );
  69.     for ( i = 9; i >= 0; --i ) {
  70.         fprintf( stdout, "%i ", i );
  71.         sleep( 1 );
  72.     }
  73.     fputs( "bye\n", stdout );
  74.  
  75.     exit( 0 );
  76. }

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].