系统有这个函数,叫daemom,我进行了模拟手动实现
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
int daemonize(int nochdir,int noclose);
{
//创建子进程,关闭父进程
int pid = fork();
if(pid > 0)
{
exit(0);
}
if(pid == -1)
return -1;
//设置文件的掩码 mode & ~umask
umask(0);
//设置文件新的回话
if(setsid() < 0)
{
perror("setsid");
return -1;
}
//设置新的目录
if(nochdir == 0)
{
chdir("/");
}
//关闭标准输入,输出,错误
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
//重定向
if(noclose == 0)
{
open("/dev/null",O_RDWR);
open("/dev/null",O_RDWR);
open("/dev/null",O_RDWR);
}
}
int main()
{
// 系统自带的 daemom
daemonize(0,0);
while(1);
return 0;
}

被折叠的 条评论
为什么被折叠?



