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>

int main()
{
	pid_t pid;
	if( (pid = fork()) < 0 )
	{
		printf("fork error.\n");
		exit(-1);
	}
	else if(pid == 0)	/* first child */
	{
		if( (pid = fork()) < 0 )
		{
			printf("fork error.\n");
			exit(-1);
		}
		else if(pid > 0)
		{
			exit(0);
		}
		
		/* We're the second child; our parent becomes init as soon as our real parent exits. */
		printf("second child, parent pid = %d\n", getppid());
		/* ---------------handle tasks--------------- */
		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);
	/* ---------------handle tasks--------------- */
	
	exit(0);
}

注意

这个代码并不是通用场景的避免僵尸进程的办法,它的场景是这样的:

一个进程要创建一个进程,两个进程同时处理任务,谁也不耽误谁。如果直接用子进程充当第二个进程的角色,那么问题是这样的:如果父进程处理时间长,子进程处理时间短,那么如果父进程不 wait() 处理的话,子进程就会成为僵尸进程,但如果父进程 wait() 子进程的话,父进程就会阻塞,所有有个方法就是让自己尽快推出,任务让子进程的子进程来处理。


这个场景的 APUE 的原文描述:If we want to write a process so that it forks a child but we don't want to wait for the child to complete and we don't want the child to become a zombie until we terminate, the trick is to call fork twice.