(trunk daemon) #1619: fix noclose error in our fallback implementation of daemon()

This commit is contained in:
Charles Kerr 2008-12-25 22:06:48 +00:00
parent 25550f03e4
commit 2a3142bf50
1 changed files with 39 additions and 66 deletions

View File

@ -16,6 +16,9 @@
#include <stdlib.h> /* exit, atoi */ #include <stdlib.h> /* exit, atoi */
#include <string.h> /* strcmp */ #include <string.h> /* strcmp */
#include <sys/types.h> /* umask*/
#include <sys/stat.h> /* umask*/
#include <fcntl.h> /* open */ #include <fcntl.h> /* open */
#include <signal.h> #include <signal.h>
#include <unistd.h> /* daemon */ #include <unistd.h> /* daemon */
@ -78,82 +81,52 @@ gotsig( int sig UNUSED )
closing = TRUE; closing = TRUE;
} }
#if !defined( WIN32 )
#if !defined( HAVE_DAEMON )
static int static int
daemon( int nochdir, tr_daemon( int nochdir, int noclose )
int noclose )
{ {
switch( fork( ) ) #if defined(HAVE_DAEMON) && !defined(WIN32)
{ return daemon( nochdir, noclose );
case 0: #else
break; pid_t pid = fork( );
if( pid < 0 )
case - 1: return -1;
tr_nerr( MY_NAME, "Error daemonizing (fork)! %d - %s", errno, else if( pid > 0 )
strerror( _exit( 0 );
errno ) ); else {
pid = setsid( );
if( pid < 0 )
return -1; return -1;
default: pid = fork( );
_exit( 0 ); if( pid < 0 )
}
if( setsid( ) < 0 )
{
tr_nerr( MY_NAME, "Error daemonizing (setsid)! %d - %s", errno,
strerror(
errno ) );
return -1;
}
switch( fork( ) )
{
case 0:
break;
case - 1:
tr_nerr( MY_NAME, "Error daemonizing (fork2)! %d - %s", errno,
strerror(
errno ) );
return -1; return -1;
else if( pid > 0 )
default:
_exit( 0 ); _exit( 0 );
} else {
if( !nochdir && 0 > chdir( "/" ) ) if( !nochdir )
{ if( chdir( "/" ) < 0 )
tr_nerr( MY_NAME, "Error daemonizing (chdir)! %d - %s", errno, return -1;
strerror(
errno ) );
return -1;
}
if( !noclose ) umask( (mode_t)0 );
{
int fd; if( !noclose ) {
if( ( ( fd = open( "/dev/null", O_RDONLY ) ) ) != 0 ) /* send stdin, stdout, and stderr to /dev/null */
{ int i;
dup2( fd, 0 ); int fd = open( "/dev/null", O_RDWR, 0 );
close( fd ); for( i=0; i<3; ++i ) {
} if( close( i ) )
if( ( ( fd = open( "/dev/null", O_WRONLY ) ) ) != 1 ) return -1;
{ dup2( fd, i );
dup2( fd, 1 ); }
close( fd ); close( fd );
} }
if( ( ( fd = open( "/dev/null", O_WRONLY ) ) ) != 2 )
{ return 0;
dup2( fd, 2 );
close( fd );
} }
} }
#endif
return 0;
} }
#endif
#endif
static const char* static const char*
getConfigDir( int argc, const char ** argv ) getConfigDir( int argc, const char ** argv )
@ -247,7 +220,7 @@ main( int argc,
#ifndef WIN32 #ifndef WIN32
if( !foreground ) if( !foreground )
{ {
if( 0 > daemon( 1, 0 ) ) if( 0 > tr_daemon( TRUE, FALSE ) )
{ {
fprintf( stderr, "failed to daemonize: %s\n", strerror( errno ) ); fprintf( stderr, "failed to daemonize: %s\n", strerror( errno ) );
exit( 1 ); exit( 1 );