#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
void create_daemon()
{
//1. 将文件模式创建屏蔽字设置为0
umask(0);
//2. 调用fork 父进程退出
// 作用:确保子进程不是一个进程组的组长
pid_t id = 0;
if ( (id = fork()) < 0)
{
perror("fork");
exit(2);
}
if(id > 0 )
{// father
exit(3);
}
// 3.调用setsid 创建一个新的会话
setsid();
//4. 将当前工作目录改为更目录
chdir("/");
//5. 关闭不需要的文件描述符
//标准输入文件stdin,标准输出文件stdout,标准错误输出文件stderr
close(0);
close(1);
close(2);
//6. 忽略SIGCHLD 信号
signal(SIGCHLD, SIG_IGN);
// 守护进程逻辑
while(1)
{
// Do something
}
}
int main()
{
create_deamon();
return 0;
}