私はブライアントとオハラロンに取り組んでいComputer Systems, A Programmer's Perspective
ます。演習 8.16 は、次のようなプログラムの出力を要求します (Web サイトでダウンロードできるヘッダー ファイルを使用しているため、変更しました):
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
int counter = 1;
int main()
{
if (fork() == 0){
counter--;
exit(0);
}
else{
Wait(NULL);
printf("counter = %d\n", ++counter);
}
exit(0);
}
親プロセスは子プロセスが終了するのを待ってからカウンターをインクリメントするため、「カウンター = 1」と答えました。しかし、子供は最初にそれを減らします。しかし、プログラムをテストしたところ、正解は「counter = 2」であることがわかりました。変数「カウンター」は子プロセスと親プロセスで異なりますか? そうでない場合、なぜ答えは 2 なのですか?