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;
}