linux环境编程中, 僵尸进程的产生和预防

    本文参考了<<unix高级环境编程>>的相关知识, 如要更详细了解请查阅之.

 

    先看一下僵尸(zombie)进程的含义吧:

    如果一个父进程先于子进程结束, 那么init成为该子进程的父进程, 而不是其祖父进程; 如果子进程先于父进程结束, 则该子进程变为僵尸进程(zombie).

   

 
/* 如果一个父进程先于子进程结束, 那么init成为该子进程的父进程, 而不是其祖父进程; 如果子进程先于父进程结束, 则该子进程变为僵尸进程. */

/* 僵尸进程产生的例子 */
用ps axu | grep Z 命令查看进程, 将发现有zombie进程产生.

#include <linux/types.h>
#include <sys/wait.h>
#include <assert.h>

    int
main(void)
{
    pid_t pid;

    if ((pid = fork()) < 0) {
        /* err_sys("fork error") */;
    } else if (pid == 0) {  /* child */
        sleep(2);
        exit(0);
    }
    printf("first child, parent pid = %d    ", getppid());

    while(1);  /* 无限循环, 使得main进程永远不会结束, 从而使得child进程成为僵尸进程(zombie). */
    assert( 0 );
    if (waitpid(pid, NULL, 0) != pid) /* wait for first child */  /* 永远不会被执行 */
        /* err_sys("waitpid error") */;

    exit(0);
}

 

/* 有效预防进程产生的方法: fork两次, 然后把第一次fork产生的子进程终止, 这样第二次fork产生的子进程的父进程就变成了init, 避免了僵尸进程的产生. */
#include <sys/wait.h>
int
main(void)
{
 pid_t pid;

 if ((pid = fork()) < 0) {
  err_sys("fork error");
 } else if (pid == 0) {  /* first child */
  if ((pid = fork()) < 0)
   err_sys("fork error");
  else if (pid > 0) {
   exit(0); /* parent from second fork == first child */ /* 终止第一个子进程 */          /* (1) */
   /* 终止第一个子进程(即第二个子进程的父进程)后, 第二个子进程的父进程变成了init, 避免了僵尸进程的产生. */

  }

  /* 除了text部分, 子进程copy父进程的所有. 所以second-child可以执行sleep(2)后的三行代码. */
  /*
   * We're the second child; our parent becomes init as soon
   * as our real parent calls exit() in the statement above.
   * Here's where we'd continue executing, knowing that when
   * we're done, init will reap our status.
   */
  /* 由于(1)的存在, first-child永远不可能执行到这. */
  sleep(2); /* 如果不sleep, second-child可能先于first-child结束. */
  printf("second child, parent pid = %d    ", getppid());
  exit(0);
 }

 if (waitpid(pid, NULL, 0) != pid) /* wait for first child */
  err_sys("waitpid error");
 /*
  * We're the parent (the original process); we continue executing,
  * knowing that we're not the parent of the second child.
  */
 exit(0);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值