编写守护进程的基本步骤

来源:互联网 发布:windows经典桌面 编辑:程序博客网 时间:2024/06/05 08:47

本文基址:http://blog.csdn.net/cugxueyu/archive/2007/12/13/1932771.aspx


#include 
<stdio.h>
#include 
<time.h>
#include 
<stdlib.h>
#include 
<sys/types.h>
#include 
<sys/stat.h>
#include 
<unistd.h>
#include 
<signal.h>
#include 
<sys/file.h>
#include 
<syslog.h>

#define daemon_main main

int daemon_main(int argc, char *argv[])
{
    
int        fd_index, fdtablesize;
    pid_t    pid;
    pid_t    child_pid;
        
    
/*@1 Ignore SIGTTOU, SIGTTIN, SIGTSTP, SIGHUP */
    signal(SIGTTOU, SIG_IGN);
    signal(SIGTTIN, SIG_IGN);
    signal(SIGTSTP, SIG_IGN);
    signal(SIGHUP,  SIG_IGN);

    
if ((pid = fork()) < 0{
        (
void)printf("parent fork error... ");    
        exit(
1);
    }


    
/*@2 parent exit */
    
if (pid > 0) exit(0);
    
    
/*@3 child process */
    
if (pid == 0{
        
/*@4 create session and set process group ID */
        
if (setsid() < 0{
            (
void)printf("setsid error... ");
            exit(
1);
        }

    }


    
/*@5 grandchild process */
    
if ((child_pid = fork()) < 0{
        (
void)printf("child fork error... ");
        exit(
1);
    }

    
    
/*@6 child process exit */
    
if (child_pid > 0{
        exit(
0);
    }


    
/*@7 close file descriptor */
    fdtablesize 
= getdtablesize();
    
for(fd_index = 0; fd_index < fdtablesize; fd_index++{
        close(fd_index);
    }


    
/*@8 choose work directory */
    
if (chdir("/tmp"< 0{
        (
void)printf("chdir error... ");
        exit(
1);
    }


    
/*@9 reset umask */
    umask(
0);

    
/*@10 ignore SIGCHLD */
    signal(SIGCHLD, SIG_IGN);

    
/*@11 open syslog test daemon */
    FILE 
*fp = fopen("/tmp/syslog""w");
    fputs(
"Daemon syslog testing... ", fp);
    
//syslog(LOG_USER | LOG_INFO, "Daemon syslog testing... ");
    while(1{        
        time_t now;
        time(
&now);
        
//syslog(LOG_USER | LOG_INFO, "Current time: %s ", ctime(&now));
        (void)fprintf(fp, "Current time: %s ", ctime(&now));
        fflush(fp);
        sleep(
5);
    }

    
return 0;
}