实现守护进程

#include <unistd.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>

void init_daemon(void)
{
    int pid;
    int i;
    if(pid = fork())
    {
    >---exit(0);
    }
    if(pid < 0)
    {
        exit(1);
    }
    setsid();
    if(pid = fork())
    {
       exit(0);
    }
    else if(pid < 0 )
    {
        exit(1);
    }

    for(i = 0; i < NOFILE; ++i)
    {
        close(i);
    }
    chdir("/tmp");
    umask(0);
    return;
}
#include <stdio.h>
#include <time.h>

void init_daemon(void);

int main()
{
    FILE *fp;
    time_t t;
    init_daemon();

    while(1)
    {
        sleep(60);
        if((fp = fopen("test.log","a")) >= 0)
        {
            t = time(0);
            fprintf(fp, "Im here at %s\n'", asctime(localtime(&t)));
            fclose(fp);
        }
    }
}


猜你喜欢

转载自blog.csdn.net/ainiding222/article/details/42742537