2016-10-06 29 views
-1

OSを学習すると、通常、すべての教科書で、親プロセスでfork()を使用して子プロセスを作成し、親プロセスでwait()を呼び出して子供の完成。OS:子プロセスで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 

それを説明する方法は?

答えて

2

しかし、私は子供の中でwait()を使用するとどうなりますか?

あなたはその文書を読んでいますか?特に戻り値とエラー条件に関する部分は?あなたが実験をしたことが分かります。それは良いことです。 wait()を呼び出すプロセスが子プロセスを待たなければ、すぐに-1を返し、エラーを示すことはすでに明らかであるはずです。この場合、errnoECHILDに設定されます。

エラーを即座に返すことは完璧な意味を持ちます。呼び出しプロセスに子がない場合は、待っている間は起こり得ないイベントに対して無期限に待つだけです。

0

サンプル出力で何が起こったのかはすでに述べていますが、waitシステムコールからエラーコードを受け取った後に、errnoの値を確認する必要があります。

#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? 
    } 
} 
if (errno == ECHILD)をチェックすることが有用であると、このエラーを処理することができるいくつかのアクションを実行するために使用することができますが、あなたはまた、次のコードを使用して、エラーメッセージの文字列(文字列)を取得することができます
関連する問題