gpt4 book ai didi

c - 子进程中的变量修改

转载 作者:行者123 更新时间:2023-12-04 02:23:28 25 4
gpt4 key购买 nike

我正在研究 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”是因为父进程等待其子进程终止然后递增计数器。但是 child 首先递减它。然而,当我测试程序时,我发现正确答案是“counter = 2”。子进程和父进程中的变量“counter”是否不同?如果不是,那为什么答案是 2?

最佳答案

您的父进程以 1 处的 counter 开始。

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

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

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

关于c - 子进程中的变量修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25413868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com