现在的位置: 首页 > 综合 > 正文

调用fork两次避免僵尸进程

2013年06月23日 ⁄ 综合 ⁄ 共 803字 ⁄ 字号 评论关闭

Avoid zombie processes by calling fork twice

/*
 * Avoid zombie processes by calling fork twice.
 * APUE-2e 程序清单8-5
 */
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include "sig_wait_proc.h"

int main()
{
	pid_t pid;
	if( (pid = fork()) < 0 )
	{
		printf("fork error.\n");
		exit(0);
	}
	else if(pid == 0)	/* first child */
	{
		init_wait();
		if( (pid = fork()) < 0 )
		{
			printf("fork error.\n");
			exit(0);
		}
		else if(pid > 0)
		{
			tell_proc(pid);	/* tell child on exiting */
			exit(0);
		}
		
		/* We're the second child; our parent becomes init as soon as our real parent exits. */
		wait_proc();	/* wait for parent */
		printf("second child, parent pid = %d\n", getppid());
		exit(0);
	}
	
	if(waitpid(pid, NULL, 0) != pid)	/* wait for first child */
	{
		printf("waitpid error.\n");
		exit(1);
	}
	printf("parent, first child pid = %d\n", pid);
	
	exit(0);
}

说明:
init_wait(),tell_proc(),wait_proc()见http://blog.csdn.net/duyiwuer2009/article/details/7948026

抱歉!评论已关闭.