daemon()函数主要用于希望脱离控制台,以守护进程形式在后台运行的程序。
#include <unistd.h>
#include <fcntl.h>
//linux daemon函数
static int Daemon(int nochdir,int noclose)
{
pid_t pid;
if(! nochdir && chdir("/") != 0 )
return -1;
if(!noclose){
int fd = open("/dev/null",O_RDWR);
if(fd < 0)
return -1;
dup2(fd,0);
dup2(fd,1);
dup2(fd,2);
close(fd);
}
pid = fork();
if(pid < 0 )
return -1;
if(pid > 0)
_exit(0);//父进程直接退出,让子进程变成孤儿进程。
if(setsid() < 0)
return -1;
return 0;
}
int main()
{
Daemon(1,1);
return 0;
}