什么是叉返回?

成功时,subprocess的PID将在父进程的执行线程中返回,并在subprocess的线程中返回0。

p = fork(); 

我在手册页混淆了,是等于0还是PID

我不确定手册是如何更清晰的! fork()创建一个新的进程,所以你现在有两个相同的进程。 为了区分它们, fork()的返回值是不同的。 在原来的过程中,你得到了子进程的PID。 在子进程中,你得到0。

所以规范使用如下:

 p = fork(); if (0 == p) { // We're the child process } else if (p > 0) { // We're the parent process } else { // We're the parent process, but child couldn't be created } 
                              p = fork();
                         / *假定没有错误* /
                         / *你现在有两个* /
                         / *程序运行* /
                          --------------------
      如果(p> 0){|  if(p == 0){
        的printf( “亲本\ n”);  | 的printf( “子\ n”);
         ... |  ...

一旦fork被执行,你有两个进程。 该调用为每个进程返回不同的值。

如果你做这样的事情

 int f; f = fork(); if (f == 0) { printf("I am the child\n"); } else { printf("I am the parent and the childs pid is %d\n",f); } 

你会看到两个消息打印。 他们正在通过两个独立的进程打印。 这是他们可以区分创建的两个过程的方式。

进程是在定向树中构建的,你只知道你的单亲( getppid() )。 简而言之, fork()像许多其他的系统函数一样返回-1错误,非零值对fork调用的发起者(父类)知道它的新子pid是有用的。

没有什么比例子:

 /* fork/getpid test */ #include <sys/types.h> #include <unistd.h> /* fork(), getpid() */ #include <stdio.h> int main(int argc, char* argv[]) { int pid; printf("Entry point: my pid is %d, parent pid is %d\n", getpid(), getppid()); pid = fork(); if (pid == 0) { printf("Child: my pid is %d, parent pid is %d\n", getpid(), getppid()); } else if (pid > 0) { printf("Parent: my pid is %d, parent pid is %d, my child pid is %d\n", getpid(), getppid(), pid); } else { printf("Parent: oops! can not create a child (my pid is %d)\n", getpid()); } return 0; } 

结果(bash是pid 2249,在这种情况下):

 Entry point: my pid is 16051, parent pid is 2249 Parent: my pid is 16051, parent pid is 2249, my child pid is 16052 Child: my pid is 16052, parent pid is 16051 

如果你需要在父母和孩子之间分享一些资源(文件,父母pid等等),看看clone() (对于GNU C库,或者其他的)

这是很酷的部分。 这等于两个。

那么,不是真的。 但是一旦fork返回, 你现在有两个程序正在运行! 两个过程。 你可以把它们当作替代宇宙。 其中一个返回值是0 。 另一方面,这是新流程的ID

通常你会有这样的东西:

 p = fork(); if (p == 0){ printf("I am a child process!\n"); //Do child things } else { printf("I am the parent process! Child is number %d\n", p); //Do parenty things } 

在这种情况下,两个字符串都将被打印,但通过不同的过程!

fork()在父进程中被调用。 然后产生一个子进程。 到子进程产生时, fork()已经完成了执行。

在这一点上, fork()已经准备好返回,但是它返回一个不同的值,这取决于它是在父类还是子类。 在子进程中,它返回0,在父进程/线程中,它返回子进程ID。

叉创建一个重复的过程和一个新的过程上下文。 当它返回一个0值时,这意味着一个子进程正在运行,但是当它返回另一个值,这意味着父进程正在运行。 我们通常使用wait语句,以便子进程完成并且父进程开始执行。

我认为它是这样工作的:当pid = fork()时,代码应该被执行两次,一个在当前进程中,一个在子进程中。 所以它解释了为什么if / else都执行。 顺序是,第一个当前进程,然后执行这个子进程。