linux下的守护(精灵)进程daemon

#include <stdio.h>
#include<fcntl.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<string.h>
#include<sys/stat.h>

int main()
{
    
    
    //0.准备变量

    pid_t pid;
    int i,fd;
    char *buf = "Run Daemon\n";
   //1.创建子进程,父进程退出
    pid = fork();
    if(pid<0)
    {
    
    
     printf("Error fork\n");
     exit(1);
    }
    else if(pid>0)
        {
    
    
        exit(0);
    }
    //2.在子进程中创建新会话
    setsid();
    //3.改变当前目录为根目录
    chdir("/");
    //4.重设文件权限掩码
    umask(0);
    //5.关闭文件描述符
    for(i = 0; i < getdtablesize();i++)  //getdtablesize 获取文件描述符的大小
        {
    
    
        close(i);
    }

    //6.守护进程要办的事情
    while(1)
        {
    
    
        if((fd = open("/tmp/daemon.log",O_CREAT|O_WRONLY|O_APPEND,0600))<0)
            {
    
    
            printf("Open file error\n");             /*让守护进程每10s写入一句话到tmp/daemon.log日志中*/
            exit(1);
        }
        write(fd,buf,strlen(buf)+1);
        close(fd);
        sleep(10);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_50188452/article/details/110263564