代码
// 创建守护进程daemon(脱离终端的进程)
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
pid_t pid,sid;
//step1:创建子进程
pid = fork();
if(pid < 0){
perror("fork erro");
exit(1);
}
else if(pid == 0)
{
printf("child process pid: %d\n",getpid());
printf("Group ID of child pgid: %d\n",getpgid(pid));
printf("Session ID of child is:%d\n",getsid(pid));
//step2:在子进程中创建会话
sid = setsid();
printf("child process pid is %d\n",getpid());
printf("Session Id of child is:%d\n",sid);
printf("Group ID of child is: %d\n",getpgid(pid));
//step3:改变当前目录为根目录
if(chdir("/") < 0){
perror("chdir error");
exit(1);
}
//step4:重设文件权限掩码
umask(0);
//关闭文件描述符
close(0);
open("/dev/null",O_RDWR);
//输入重定向
dup2(0,1);
dup2(0,2);
}
for (;;)
{
;
}
return 0;
}