linux进程控制编程,介绍守护进程编写的步骤

代码分析

  程序分析

//daemon.c
//1.创建子进程,父进程退出
//2.在子进程中创建新会话
//3.改变当前目录为根目录
//4.重设文件权限掩码
//5.关闭文件描述符


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

int main()
{
	pid_t pid;
	int i, fd;
	char *str = "This is my first daemon process\n";

	pid = fork();			//step1 创建子进程
	if (pid < 0)
	{
		printf("Error fork\n");
		exit(-1);
	}
	else if(pid > 0)
	{
		exit(0);			//step1 父进程退出,让子进程变成孤儿进程
	}
	
	//setsid - creates a session and sets the process group ID
	//#include <unistd.h>
	//pid_t setsid(void);
	setsid();				//step2 在子进程中创建新会话
	//具体有以下作用
	//让进程摆脱原会话的控制。
	//让进程摆脱原进程组的控制。
	//让进程摆脱原控制终端的控制。


	//chdir, fchdir - change working directory
	//#include <unistd.h>
	//int chdir(const char *path);
	//int fchdir(int fd);
	chdir("/");				//step3 改变当前目录为根目录
	
	//umask - set file mode creation mask
	//#include <sys/types.h>
	//#include <sys/stat.h>
	//mode_t umask(mode_t mask);
	umask(0);				//step4 重设文件权限掩码
	
	//getdtablesize - get descriptor table size
	//#include <unistd.h>
	//int getdtablesize(void);
							//step5 关闭文件描述符
							//主要是因为,0,1,2三个描述符对守护进程来说已经失去了意义
	for(i=0; i<getdtablesize(); i++)		
	{
		close(i);
	}
	while(1)				
	{
		fd = open("/tmp/daemon.log",O_CREAT|O_WRONLY|O_APPEND, 0600);
		if (fd < 0)
		{
			printf("Error Open file\n");
			exit(-1);
		}
		write(fd, str, strlen(str) + 1);
		close(fd);
		sleep(10);
	}
	exit(0);
}