进程——守护进程

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>

// 如果成功,返回1,失败返回0
int daemonize()
{
	// 1、创建子进程,关闭父进程
	pid_t pid = fork();
	if (pid > 0)
	{
		exit(0);
	}
	else if (pid < 0)
	{
		return 0;
	}
	
	// 2、设置文件掩码,新创建文件的默认权限
	umask(0);
	
	// 3、启动新的会话,将当前进程设置为新会话的首领
	pid_t sid = setsid();
	if (sid < 0)
	{
		return 0;
	}

	// 4、改变当前的工作目录
	if (chdir("/") < 0)
	{
		return 0;
	}
	
	// 5、关闭不使用的文件描述符
	close (STDIN_FILENO);
	close (STDOUT_FILENO);
	close (STDERR_FILENO);
	
	// 6、重定向标准输入,标准输出、标准错误
	open ("/dev/null", O_RDONLY);    // 0
	open ("/dev/null", O_RDWR);      // 1
	open ("/dev/null", O_RDWR);      // 2
	
	return 1;
}


int main()
{
	daemonize();
	while(1);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ypjsdtd/article/details/86517855