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
それを説明する方法は?