4
Launch a demon
- /*
- * Creates a daemon process.
- *
- * fork
- * setsid
- * chdir
- */
- #include <sys/types.h>
- #include <unistd.h>
- #include <signal.h>
- #include <fcntl.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #if defined( LINUX )
- #include <string.h>
- #endif
- int main( int argc, char **argv ) {
- int pid;
- int i, fd;
- pid = fork();
- if ( pid == -1 ) { /* error */
- fprintf( stderr, "%s\n", strerror( errno ) );
- exit( 1 );
- }
- if ( pid != 0 ) /* parent */
- exit( 0 );
- /* child */
- setsid();
- pid = fork();
- if ( pid == -1 ) { /* error */
- fprintf( stderr, "%s\n", strerror( errno ) );
- exit( 1 );
- }
- if ( pid != 0 ) /* parent */
- exit( 0 );
- /* child */
- chdir( "/" );
- umask( 0 ); /* or 027 */
- /* catch signals */
- signal( SIGHUP, SIG_IGN );
- signal( SIGINT, SIG_IGN );
- signal( SIGTERM, SIG_IGN );
- /* close all descriptors */
- for ( fd = getdtablesize(); i >= 0; --i )
- close( fd );
- /* reopen standard io */
- fd = open( "/dev/null", O_RDWR ); /* stdin */
- fd = open( "/dev/console", O_WRONLY ); /* stdout */
- fd = open( "/dev/null", O_WRONLY ); /* stderr */
- setbuf( stdout, 0 );
- fprintf( stdout, "kill %i\n", getpid() );
- for ( i = 9; i >= 0; --i ) {
- fprintf( stdout, "%i ", i );
- sleep( 1 );
- }
- fputs( "bye\n", stdout );
- exit( 0 );
- }
Comments