fork()和更改局部变量? [英] fork() and changing local variables?
问题描述
我试图理解fork()的概念,有一件事我似乎无法理解.
I am trying to understand the fork() concept and there's is one thing I can't seem to understand.
在以下代码中-为什么即使子进程将其更改为5,父级仍会打印i = 0?
In the following code - why does the parent still print i=0 even when child process changes it to 5?
wait(NULL)阻止父进程,直到子进程先完成.
The wait(NULL) blocks parent process until child finishes first.
int main(int argc, char *argv[]) {
int i = 0;
if (fork() == 0) {
i = 5;
} else {
wait(NULL);
printf("i = %d\n", i);
}
return 0;
}
有人可以解释为什么我的假设不正确吗?
Can somebody explain why my assumption is incorrect?
推荐答案
进程之间不共享变量.调用fork
之后,有两个完全独立的过程. fork
在子级中返回0,其中局部变量设置为5.在父级中,fork
返回子级的进程ID,i
的值不变.在调用fork
之前,它仍然具有设置为0的值.就像您有两个程序单独运行一样,行为相同:
Variables are not shared between processes. After the call to fork
, there are two completely separate processes. fork
returns 0 in the child, where the local variable is set to 5. In the parent, where fork
returns the process ID of the child, the value of i
is not changed; it still has the value 0 set before fork
was called. It's the same behavior as if you had two programs run separately:
int main(int args, char *argv[]) {
int i=0;
printf("i = %d\n", i);
return 0;
}
和
int main(int argc, char *argv[]) {
int i = 0;
i = 5;
return 0;
}
这篇关于fork()和更改局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!