简体   繁体   English

C语言中的Fork()程序

[英]Fork() program in C

so I am attempting to solve a problem in my book regarding the fork system call in C. 所以我试图解决我的书中有关C语言中fork系统调用的问题。

Here is the following code: 这是下面的代码:

#include <stdio.h>
#include <unistd.h>

int main() {  

int i = 1;

   if (fork ()) //parent process will return PID of child.
        i++;
   else if (fork()) //child process (becomes parent)
            i--;
       else //grandchild process returns 0
            i++;

 printf("%d\n", i);
}

After going through the code, I got 2 0 2 as the solution. 看完代码后,我得到2 0 2作为解决方案。 I am confused though since I don't know which order is correct? 我很困惑,因为我不知道哪个顺序正确? Can the child processes get printed out before the parent does? 子进程可以在父进程之前打印出来吗? If so, another viable solution could be 0 2 2 or 2 2 0. How do I know if all the conditional statements will be executed? 如果是这样,另一个可行的解决方案可能是0 2 2或2 20。我如何知道是否将执行所有条件语句? I know in the first conditional, the if statement will be executed and will be the parent process (which will return the process ID of the child, and the value of i will increment to 2). 我知道在第一个条件中, if语句将被执行并将成为父进程(它将返回子进程的ID,i的值将增加到2)。 How would I know if the else if and else code will be executed? 我怎么知道是否将执行else if and else代码? Sorry, I am just confused and trying to wrap my head around this as this is a new topic for me. 抱歉,我只是糊涂了,试图绕过这个话题,因为这对我来说是一个新话题。

Any help would be greatly appreciated. 任何帮助将不胜感激。 Thank you in advance. 先感谢您。

The child process can be printed before the parent finishes. 可以在父进程完成之前打印子进程。 Remember, in the parent process, the call to fork() returns a nonzero number, while in the child it will return 0. 请记住,在父进程中,对fork()的调用返回一个非零数字,而在子进程中,它将返回0。

#include <stdio.h>
#include <unistd.h>

int main() {  

int i = 1;

   if (fork ())
        i++;
   else if (fork())
            i--;
       else
            i++;

 printf("%d\n", i);
}

For the above code, the parent will execute the first if() statement, the child will execute the else if statement and the grandchild will execute the else statement. 对于上面的代码,父级将执行第一个if()语句,子级将执行else if语句,孙子级将执行else语句。 The child/grandchild/parent can be printed in any order. 子/孙/父母可以以任何顺序打印。 So, 2 0 2, 2 2 0 and 0 2 2 are all viable solutions. 因此,2 0 2,2 2 0和0 2 2都是可行的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM