簡體   English   中英

操作系統:子進程中的wait()

[英]OS: wait() in child process

在學習操作系統方面,通常在任何教科書中都可以看到,在父進程中使用fork()創建子進程,有時在父進程中調用wait()以等待子進程的完成。

但是,如果我在孩子中使用wait()會發生什么?

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int
main(int argc, char** argv){
  int x;
  int w1, w2;
  x = 100;
  printf("the initialized x is: %d\n",x);
  int rc = fork();
  if(rc < 0){
    fprintf(stderr, "fork failed.\n");
    exit(1);
  }
  else if(rc == 0){
    //x = 200;                                                                  
    w1 = wait(NULL);
    printf("the x in child process (pid:%d) is: %d\n", (int) getpid(), x);
  } else {
    x = 300;
    w2 = wait(NULL);
    printf("the x in parent process (pid:%d) is: %d\n",(int) getpid(), x);
  }
  printf("the x in the end is: %d\n",x);
  printf("the returns of waits: %d, %d\n",w1,w2);
  return 0;
}

此段代碼運行並顯示以下內容:

dhcp175:hw_ch5 Suimaru$ ./a.out 
the initialized x is: 100
the x in child process (pid:18844) is: 100
the x in the end is: 100
the returns of waits: -1, 0
the x in parent process (pid:18843) is: 300
the x in the end is: 300
the returns of waits: 0, 18844

怎么解釋呢?

但是,如果我在孩子中使用wait()會發生什么?

您已閱讀其文檔? 特別是有關返回值和錯誤條件的部分? 我發現您進行了一項實驗,這很好。 在該文檔與文檔之間,應該已經很清楚的是,如果調用wait()進程沒有要等待的子進程,那么它會立即返回-1 ,這表明存在錯誤。 在這種情況下, errno將設置為ECHILD

立即返回錯誤是很有意義的,如果調用進程沒有子進程,則另一個唯一的選擇就是讓它無限期地等待一個事件,只要它一直在等待。

您已經說過示例輸出中會發生什么,但是要獲得更多詳細信息,您必須在從wait系統調用中接收到失敗代碼后,檢查errno值。 在檢查if (errno == ECHILD)是否有用並且可以用來執行一些可能處理此錯誤的操作時,您還可以使用以下代碼獲取包含錯誤消息的字符串(字符數組):

#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>

...

char err_msg[4096]; // a buffer big enough to hold an error message
errno = 0; // clear errno just in case there was an earlier error
pid_t fpid = fork();
if (fpid < 0)
{
    perror("fork failed.\n"); // prints out an error string based on errno
    exit(1);
} else if (fpid == 0)
{ // in child
    pid_t wpid = wait(NULL);                                                             
    strerror_r(errno, err_msg, sizeof(err_msg)); // gets an error string
    printf("child process (pid:%d), wpid:%d, %s\n", (int) getpid(), (int)wpid, err_msg);
} else {
    int err_val;
    wpid = wait(NULL);
    err_val = errno;
    errno = 0; // reset errno
    strerror_r(err_val , err_msg, sizeof(err_msg)); // gets an error string
    printf("parent process (pid:%d), wpid:%d, %s\n", (int) getpid(), (int)wpid, err_msg);
    if (err_val != 0)
    {
        // there was an error, so what are you going to do about it?
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM