问题描述
我正在研究Bryant和O'Hallaron的计算机系统,程序员的观点
.练习8.16要求提供如下程序的输出(我更改了程序,因为他们使用了可以在其网站上下载的头文件):
I am working on Bryant and O'Hallaron's Computer Systems, A Programmer's Perspective
. Exercise 8.16 asks for the output of a program like (I changed it because they use a header file you can download on their website):
#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.但是孩子首先要减少它.但是,当我测试该程序时,我发现正确的答案是"counter = 2".子进程和父进程中的变量"counter"是否不同?如果没有,那么答案为何2?
I answered "counter = 1" because the parent process waits for its children to terminate and then increments counter. But the child first decrements it. However, when I tested the program, I found that the correct answer was "counter = 2". Is the variable "counter" different in the child and in the parent process? If not, then why is the answer 2?
推荐答案
您的父进程以 1
处的 counter
开始.
Your parent process starts with counter
at 1
.
然后等待分叉的子进程完成.
Then it waits for the forked child process to finish.
(分叉进程中发生的任何事情都不会影响父级 counter
的版本.每个进程都有自己的内存空间;不共享任何变量.)
(Whatever happens in the forked process, does not affect the parent's version of counter
. Each process has its own memory space; no variables are shared.)
然后,最后 printf()
语句首先使用 ++
运算符将 counter
递增,这使 counter
获取值 2
.
And, finally the printf()
statement first increments counter
with the ++
operator, this makes counter
get the value 2
.
这篇关于子进程中的变量修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!