如何在下面的程序中,父进程的局部变量充当三个子进程之间的共享变量。
int main()
{
int turn = 0;
int i;
for (i = 0; i < 3; i++)
{
if (fork() == 0)
{
int me = i;
while (turn != me)
/*do nothing*/ ;
// my turn
printf("Process %d ran\n", me);
turn++;
}
}
return 0;
}
输出:
流程0运行
流程1运行
流程2运行
但据我所知,最后两个进程应该挂起,因为turn的值永远不会改变它们。
如果我放一个出口(0);在转换++之后,我立即返回到我的shell提示符,只有一行输出,即: 流程0运行
但是其他两个进程仍然在后台运行,而其他两个进程都没有输出。
答案 0 :(得分:2)
发生了什么:
main process is 0.
process 0 calls fork. i = 0;
process 0 returns from fork = 1;
process 0 calls fork. i = 1;
process 0 returns from fork = 2;
process 0 calls fork. i = 2;
process 0 returns from fork = 3;
process 0 exists;
process 1 returns from fork. i = 0;
process 1 hits the while loop turn = 0, i = 0, me = 0, while loop exists;
process 1 calls printf.
process 1 increments turn, turn = 1;
process 1 goes back to the for loop;
process 1 calls fork, i = 1;
process 1 returns from fork = 4;
process 1 calls fork, i = 2;
process 1 returns from fork = 5;
process 1 exists;
process 2 returns from fork. i = 1;
process 2 hits the while loop turn = 0, i = 1, me = 0, while loop spins forever;
process 3 returns from fork, i = 2;
process 3 hits the while loop turn = 0, i = 2, me = 0, while loop spins forever;
process 4 (spawned from process 1) returns from fork, i = 1, turn = 1 (inherited from process 1).
process 4 hits the while loop turn = 1, i = 1, me = 1, while loop exits;
process 4 calls printf;
process 4 increments turn, turn = 2;
process 4 goes back to the for loop;
process 4 calls fork, i = 2, turn = 2;
process 4 returns from fork = 6;
process 4 exits;
process 5 (spawned from process 1) return from fork, i = 2, turn = 1 (inherited from process 1)
process 5 hits the while loop turn = 1, i = 2, me = 2, while loop spins forever;
process 6 (spawned from process 4) returns from fork i = 2, turn = 2 (inherited from process 4)
process 6 hits the while loop turn = 2, i = 2, me = 2, while loop exists;
process 6 calls printf;
process 6 drops out of the for loop
process 6 exits;
基本上,你需要记住你将继续运行for循环的所有进程,而不仅仅是主进程。在那之后,要弄清楚发生了什么并不是很难。您总共产生了6个进程,其中3个进程的状态为i
和turn
。
答案 1 :(得分:2)
重构您的代码:
#include <unistd.h>
#include <stdio.h>
int main()
{
int turn = 0;
int i;
for (i = 0; i < 3; i++)
{
printf("forking i = %d, turn = %d\n", i, turn);
if (fork() == 0)
{
int me = i;
while (turn != me)
/*do nothing*/ ;
// my turn
printf("Process %d ran\n", me);
turn++;
}
}
return 0;
}
这可能会给你带来震撼,但正如上面的Art重构显示你的代码会产生6个进程。在那里放置更多的printfs应该让你了解真正发生的事情。
答案 2 :(得分:-2)
在子进程共享fork()之前声明的变量。您可以通过打印和循环来检查它。它会是一样的。