3

我正在研究 Bryant 和 O'Hallaron 的Computer Systems, A Programmer's Perspective. 练习 8.16 要求一个程序的输出,比如(我改变了它,因为他们使用了一个你可以在他们的网站上下载的头文件):

#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);
}

我回答“counter = 1”是因为父进程等待其子进程终止,然后递增计数器。但孩子首先减少它。然而,当我测试程序时,我发现正确的答案是“counter = 2”。子进程和父进程中的变量“计数器”是否不同?如果不是,那为什么答案是 2?

4

1 回答 1

4

您的父进程以counterat开头1

然后它等待分叉的子进程完成。

(无论在分叉进程中发生什么,都不会影响父进程的版本counter。每个进程都有自己的内存空间;不共享任何变量。)

最后,该语句首先使用运算符printf()递增,这使得获取值。counter++counter2

于 2014-08-20T21:08:35.737 回答