创建守护进程

守护进程:系统一开启就默默在后台执行,结束关闭。

1.创建子进程,父进程退出。//fork()&exit()
2.在子进程中创建新会话。//setsid()
3.将当前目录改为根目录or\tmp。 //chdir(“\tmp”)
4.重设权限掩码。//umask(0)
5.关闭文件描述符。//getdtablesize():系统能最大打开文件描述符个数

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

void mydaemon();
int main(int argc, char *argv[])
{ 
    mydeamon();
    //守护进程实现功能:在后台每隔1s往1.txt里写入hello,要换行
    FILE *fp = fopen("1.txt","a+");
    if(NULL == fp)
    {
        perror("fopen");
        return -1;
    }
    while(1)
    {
        sleep(1);
        fprintf(fp,"%s\n","hello");
        fflush(fp);//标准IO的buffer缓冲机制
    }
    return 0;
}

//创建守护进程
void mydaemon()
{
    pid_t pid = fork();//创建子进程
    if(pid < 0)
    {
        perror("fork");
        exit(-1);
    }else if(pid == 0)
    {
        if(-1 == setsid())//创建新会话
        {
            perror("setsid");
            exit(-1);
        }
        if(-1 == chdir("/tmp"))//改变当前目录为/tmp
        {
            perror("chdir");
            exit(-1);
        }
        umask(0);//重设权限掩码
        for(int i = 0;i < getdtablesize();i++)//关闭所有文件描述符
        {
            close(i);
        }
    }else{
        exit(0);//父进程退出
    }
}