[英]Another Fork() program in C
So I am continuing some more problems on Fork() and found some sample code on a website called geeksforgeeks. 因此,我在Fork()上继续遇到更多问题,并在名为geeksforgeeks的网站上找到了一些示例代码。 The following code segment: 以下代码段:
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
void forkexample()
{
int x = 1;
if (fork() == 0)
printf("Child has x = %d\n", ++x);
else
printf("Parent has x = %d\n", --x);
}
int main()
{
forkexample();
return 0;
}
Now I can see why the solution can be either Child has x = 2 and Parent has x = 0 but I am having some issues trying to visualize the tree. 现在,我明白了为什么解决方案可以是“ 孩子”有x = 2而“ 父”有x = 0,但是我在尝试可视化树时遇到了一些问题。 The big problem that I have visualizing this is that the first if statement is for the child process, so how would the tree look? 我想像的最大问题是,第一个if语句用于子进程,那么树的外观如何? Here is what I have come up with in terms of a visualization of this program. 这是我根据该程序的可视化得出的结果。
Or would the main node on Level 0 be a Child node because of the order of the if statement coming first (this is a possibility but the else statement could come first as well as it is running concurrently). 或者,由于if语句排在最前面(这是可能的,但else语句可以排在前面并同时运行),因此级别0上的主节点将成为子节点。
Any help? 有什么帮助吗? Is this visualization correct or is there something I am missing? 这种可视化是否正确,或者我缺少什么?
Would appreciate the help , thank you. 谢谢您的帮助,谢谢。
No, your visualization is wrong. 不,您的可视化是错误的。
After the fork you have TWO processes: Parent and Child. 分叉之后,您有两个过程:父级和子级。 (PERIOD) (期)
A single parent may spawn multiple children, and each may spawn children of their own. 单亲父母可能会产生多个孩子,每个人可能会产生自己的孩子。 But after a single fork, the "tree" is two "nodes". 但是在一个分支之后,“树”是两个“节点”。
Not sure if you are trying to graph: 不确定是否要绘制图形:
I don't see where the question is here.. 我看不出问题在哪里..
The schema is good it's like this. 模式很好,就像这样。 Fork() creates a new process by duplicating the calling process. Fork()通过复制调用过程来创建一个新过程。 On success, the PID of the child process is returned in the parent, and 0 is returned in the child. 成功后,将在父级中返回子进程的PID,在子级中返回0。 On failure, -1 is returned in the parent, no child process is created (google). 如果失败,则在父级中返回-1,不会创建任何子级进程(google)。 You must check the return value to be sure that you're in the child process which is running independently. 您必须检查返回值,以确保您处于独立运行的子进程中。
Try this : 尝试这个 :
#include <unistd.h>
int main()
{
pid_t p;
int x;
x = 1;
p = fork();
printf("pid = %d\n", p);
if (p == 0) {
printf("Child has x = %d and pid = %d\n", ++x, p);
sleep(1);
} else {
printf("Parent has x = %d and pid = %d\n", --x, p);
sleep(1);
}
}
They are executed at the same time because they are independant but the parent is primary at the ouput 由于它们是独立的,因此它们同时执行,但父级在输出时是主要的
Nicolas 萨科
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.