在unix中使用ac程序使用fork()系统调用
嘿,我想知道以下代码的输出是什么:-
main()
{
fork();
fork();
fork();
printf("hello world");
}
我认为它应该打印 hello world 4 次。 请帮助我。
Hey i want to know what will be output of following code:-
main()
{
fork();
fork();
fork();
printf("hello world");
}
I think it should print hello world 4 times.
Plz help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它将打印 8 次 (2 ^ 3):每个 fork 都会生成一个额外的进程 - 因此每一步都会有 2 个进程(父进程和子进程),并且每个进程都会在 fork 之后的步骤中继续执行。
所以先分叉-> 2 个进程中的每一个都会进入第二个分支,在其中生成 2 个额外的进程,因此现在有 4 个进程,每个进程进入第三个分支,每个进程都会生成一个额外的进程 - 所以 8 个进程进入 printf 行!
it will print it 8 times (2 ^ 3): each fork generates an extra process -- so you end up with 2 processes at each step (the parent and the child) and each of them continue execution at the step right after the fork.
So first fork -> 2 processes each one of these going to 2nd fork in which you generate 2 extra processes so you have now 4 processes each going into the 3rd fork where each generates an extra process -- so 8 processes going into the line with printf!
每个分叉都会创建一个新的子项。每个孩子都有与父母相同的代码。所以孩子们也会分叉。
所以父母有3个孩子。
Child1 有 2 个孩子。
Child2 有 1 个孩子。
Child11 有 1 个孩子。
总共8个进程。 8 打印
Each fork creates a new child. Each child has the same code as the parent. So the children will also fork.
So Parent has 3 children.
Child1 has 2 children.
Child2 has 1 child.
Child11 has 1 child.
Total 8 processes. 8 printf
它将打印 2^3=8 次。请记住,每次调用 fork 时,您都在创建一个子进程,该子进程将在分叉后立即继续执行,因此它本身也可以分叉。这棵树看起来像这样。
Forked4---Forked5 -------------- Forked6
Forked7
因此,我们总共将有 8 个进程(主进程和 7 个分支进程)运行并打印 print 语句。
附带说明:如果 print 语句位于分叉之前,则新分叉的进程不会执行它。
It will print it 2^3=8 times. Remember, every time you call fork, you are creating a child process, that child process will continue the execution from right after it got forked so it can itself also fork. The tree will look like this.
Forked4---Forked5 -------------- Forked6
Forked7
So we will have total of 8 process (main process and 7 forked processes)running and printing the print statement.
As a side note: if the print statement was before a fork, it would not get executed by newly forked process.