Changeset 2514
- Timestamp:
- Jul 27, 2007, 2:25:28 AM (15 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/daemon/misc.c
r2417 r2514 29 29 #include <fcntl.h> 30 30 #include <stdlib.h> 31 #include <stdio.h> 31 32 #include <string.h> 32 33 #include <unistd.h> … … 209 210 daemon( int nochdir, int noclose ) 210 211 { 211 pid_t child; 212 int null; 213 214 child = fork(); 215 if( 0 > child ) 216 return -1; 217 else if( 0 != child ) 218 exit( 0 ); 219 220 if( 0 > setsid() ) 221 return -1; 222 223 if( !nochdir && 0 > chdir( "/" ) ) 224 return -1; 225 226 if( !noclose ) 227 { 228 null = open( "/dev/null", O_RDWR ); 229 if( 0 > null ) 212 switch( fork( ) ) { 213 case 0: 214 break; 215 case -1: 216 fprintf( stderr, "Error daemonizing (fork)! %d - %s\n", errno, strerror(errno) ); 230 217 return -1; 231 if( 0 > dup2( null, 0 ) || 0 > dup2( null, 1 ) || 0 > dup2( null, 2 ) ) 218 default: 219 _exit(0); 220 } 221 222 if( setsid() < 0 ) { 223 fprintf( stderr, "Error daemonizing (setsid)! %d - %s\n", errno, strerror(errno) ); 224 return -1; 225 } 226 227 switch( fork( ) ) { 228 case 0: 229 break; 230 case -1: 231 fprintf( stderr, "Error daemonizing (fork2)! %d - %s\n", errno, strerror(errno) ); 232 232 return -1; 233 close( null ); 234 } 235 236 return -1; 233 default: 234 _exit(0); 235 } 236 237 if( !nochdir && 0 > chdir( "/" ) ) { 238 fprintf( stderr, "Error daemonizing (chdir)! %d - %s\n", errno, strerror(errno) ); 239 return -1; 240 } 241 242 if( !noclose ) { 243 int fd; 244 fd = open("/dev/null", O_RDONLY); 245 if( fd != 0 ) { 246 dup2( fd, 0 ); 247 close( fd ); 248 } 249 fd = open("/dev/null", O_WRONLY); 250 if( fd != 1 ) { 251 dup2( fd, 1 ); 252 close( fd ); 253 } 254 fd = open("/dev/null", O_WRONLY); 255 if( fd != 2 ) { 256 dup2( fd, 2 ); 257 close( fd ); 258 } 259 } 260 261 return 0; 237 262 } 238 263
Note: See TracChangeset
for help on using the changeset viewer.