对大多数人来说,看起来可能是幼稚的,但我无法理解这段小小的代码。为什么输出打印两次?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char** argv) {
int i, pid;
pid = fork();
printf("Forking the pid: %d\n",pid);
for(i =0; i<5; i++)
printf("%d %d\n", i,getpid());
if(pid)
wait(NULL);
return (0);
}
停止把这个程序的是
Forking the pid: 2223
0 2221
1 2221
2 2221
3 2221
4 2221
Forking the pid: 0
0 2223
1 2223
2 2223
3 2223
4 2223
Press [Enter] to close the terminal ...
在for循环printf命令被使用一次。为什么“分叉pid”,然后再打印两次pid。这是如何工作的?有人可以解释我吗?提前致谢。 有人可以解释我为什么要在这里等待吗?我从手册页中了解到的是等待将控制权转回到父进程?我所理解的是正确的吗?分流后是否需要等待? 操作系统:ubuntu,编译器:gcc,IDE:netbeans
呃......但那正是叉子的功能!你分叉了这个过程以及fork完成两次后的所有事情,因为现在你有两个*进程!你基本上是问为什么'叉'叉! – AnT 2010-09-29 14:48:37
[此C代码可以做什么?]可能的重复(http://stackoverflow.com/questions/3730429/what-does-this-c-code-do) – 2010-09-29 14:49:52
它不是任何其他问题的重复,但可能是您提供的链接将帮助我进一步了解分叉。 – narayanpatra 2010-09-29 15:12:59