c - 關於waitpid函數的一個疑問
天蓬老师
天蓬老师 2017-04-24 09:09:05
0
1
565

"深入理解計算機係統"一書中的兩個例子, 利用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。

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回覆(1)
洪涛

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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板