守护进程的创建

基本思想:首先创建一个子进程,然后子进程杀死父进程,信号处理所有的工作由子进程来处理

/**************************************
*  
* Author : fxHui
*
* Histtory :2019-8-18
***************************************/

#include <string.h> // 使用strerror
#include <errno.h>

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

#define SLEEP_TIME 10  /* 睡眠时间 10 秒钟 */
#define MAIL "/var/spool/mail/hoyt" /* Linux默认的登陆用户邮箱 */

int main(int argc, char **argv)
{
	pid_t child;
	
	if ((child=fork()) == -1)
	{
		printf("Fork Error: %s\n", strerror(errno));
		return -1;
	}
	else if (child > 0)
	{
		if (kill(getppid(), SIGTERM) == -1)
		{
			printf("Kill Parent Error : %s\n", strerror(errno));
			return -1;
		}
		
		int mailfd;
		while (1)
		{
			if ((mailfd = open(MAIL, O_RDONLY)) != -1)
			{
				fprintf(stderr, "%s", "\007");
				close(mailfd);
			}
			sleep(SLEEP_TIME);
		}
	}
	
	return 0;
}
发布了91 篇原创文章 · 获赞 75 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/fengxianghui01/article/details/99705523