开发者社区> 问答> 正文

关于waitpid函数的一个问题

"深入理解计算机系统"一书中的两个例子, 利用waitpid函数回收僵死子进程。

#include "csapp.h"
#define N 30

int main()
{
  int status, i;
  pid_t pid;
  
  for (i = 0; i < N; i++)
    if ((pid = Fork()) == 0)
      exit(100+i);
  
  while ((pid = waitpid(-1, &status, 0)) > 0) {
    if (WIFEXITED(status))
      printf("child %d terminated normally with exit status=%d\n",
         pid, WEXITSTATUS(status));
    else
      printf("child %d terminated abnormally\n", pid);
  }
  
  if (errno != ECHILD)
    unix_error("waitpid error");
  
  exit(0);

另一个程序对这个程序稍作改动:

#include "csapp.h"
#define N 30

int main()
{
  int status, i;
  pid_t pid[N], retpid;
  
  for (i = 0; i < N; i++)
    if ((pid[i] = Fork()) == 0)
      exit(100+i);
  
  i = 0;
  while ((retpid = waitpid(pid[i++], &status, 0)) > 0) {
    if (WIFEXITED(status))
      printf("child %d terminated normally with exit status=%d\n",
         retpid, WEXITSTATUS(status));
    else
      printf("child %d terminated abnormally\n", retpid);
  }

  if (errno != ECHILD)
    unix_error("waitpid error");
  
  exit(0);
}

书上说第一个程序不会按照创建进程的顺序回收僵死进程,而第二个会。然而我实验的结果却是两者都是按创建顺序回收的,为什么会这样?环境是ubuntu。

展开
收起
杨冬芳 2016-05-30 11:09:27 2037 0
1 条回答
写回答
取消 提交回答
  • IT从业

    因为你的进程是在fork之后exit,可能会造成这种巧合的情况,但是如果你的程序干一些事情。比如你可以尝试让进程随机睡眠n秒,然后再exit,这样第一种方法显然不大可能会凑效了。

    2019-07-17 19:19:21
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载