void
setdaemon(
void
)
{
pid_t pid;
if ((pid = fork()) < 0 ){
mylog( " fork1 failed " );
exit( - 1 );
}
if (pid){
exit( 0 );
}
setsid();
if ((pid = fork()) < 0 ){
fprintf(stderr, " fork2 failed " );
exit( - 1 );
}
if (pid){
exit( 0 );
}
write_pidfile();
/*
chdir("/");
umask(0);
*/
}
void write_pidfile( void )
{
int fd;
char buff[ 20 ];
if ((fd = open( " send.pid " , O_CREAT | O_WRONLY, 0600 )) >= 0 )
{
bzero(buff, sizeof (buff));
sprintf(buff, " %5d\n " , ( int )getpid());
if (write(fd, buff, strlen(buff)) == - 1 )
mylog( " Error writing to pid file send.pid " );
( void )close(fd);
return ;
}
{
pid_t pid;
if ((pid = fork()) < 0 ){
mylog( " fork1 failed " );
exit( - 1 );
}
if (pid){
exit( 0 );
}
setsid();
if ((pid = fork()) < 0 ){
fprintf(stderr, " fork2 failed " );
exit( - 1 );
}
if (pid){
exit( 0 );
}
write_pidfile();
/*
chdir("/");
umask(0);
*/
}
void write_pidfile( void )
{
int fd;
char buff[ 20 ];
if ((fd = open( " send.pid " , O_CREAT | O_WRONLY, 0600 )) >= 0 )
{
bzero(buff, sizeof (buff));
sprintf(buff, " %5d\n " , ( int )getpid());
if (write(fd, buff, strlen(buff)) == - 1 )
mylog( " Error writing to pid file send.pid " );
( void )close(fd);
return ;
}
}
本文转自 OldHawk 博客园博客,原文链接:http://www.cnblogs.com/taobataoma/archive/2007/08/30/875596.html,如需转载请自行联系原作者