调用 fork 两次避免僵尸进程

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.



  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值