在下面的程序中,父进程的局部变量如何充当三个子进程之间的共享变量。
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 运行
但根据我的说法,最后两个进程应该挂起,因为它们的值永远不应该改变。
此外,如果我设置退出(0);在turn++之后,我立即返回到我的shell提示符,只有一行输出,即: 进程 0 运行
但其他两个进程仍然在后台运行,并且其他两个进程没有任何输出。
最佳答案
发生了什么事:
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 个进程,其中三个将具有正确的 i
和 turn
状态。
关于c - 父局部变量充当三个 child 之间的共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24263461/