模拟daemon函数

#include<unistd.h>
#include<stdio.h>
#include<pwd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/wait.h>
int main()
{
	pid_t pid ;
	pid = fork();//创建子进程
	if(pid < 0)
	{
		perror("创建子进程失败");
		return -1;
	}
	else if(pid > 0)//结束父进程
	{
		_exit(0);
	}
	else
	{
		//关闭三个文件描述符
		close(STDIN_FILENO);
		close(STDOUT_FILENO);
		close(STDERR_FILENO);
		umask(0);//重设umask
		if(setsid()<0)//setsid()自己独立建一个进程组(和一个会话)
		{
			perror("setsid");
			return -1;
		}
		for(;;)//为了演示效果
		{}
	}
}

你可能感兴趣的:(模拟daemon函数)