c - C 中的 Fork() 函数

标签 c linux process operating-system

下面是 Fork 函数的一个例子。下面也是输出。我的主要问题与 fork 有关,称为值如何更改。所以 pid1,2 和 3 从 0 开始,随着 fork 的发生而改变。这是因为每次发生 fork 时,值都会被复制到子项中,而父项中的特定值会发生变化吗?基本上,值是如何随着 fork 函数变化的?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
    pid_t pid1, pid2, pid3;
    pid1=0, pid2=0, pid3=0;
    pid1= fork(); /* A */
    if(pid1==0){
        pid2=fork(); /* B */
        pid3=fork(); /* C */
    } else {
        pid3=fork(); /* D */
        if(pid3==0) {
            pid2=fork(); /* E */
        }
        if((pid1 == 0)&&(pid2 == 0))
            printf("Level 1\n");
        if(pid1 !=0)
            printf("Level 2\n");
        if(pid2 !=0)
           printf("Level 3\n");
        if(pid3 !=0)
           printf("Level 4\n");
       return 0;
    }
}

然后就是执行了。

----A----D--------- (pid1!=0, pid2==0(as initialized), pid3!=0, print "Level 2" and "Level 4")
    |    |
    |    +----E---- (pid1!=0, pid2!=0, pid3==0, print "Level 2" and "Level 3")
    |         |
    |         +---- (pid1!=0, pid2==0, pid3==0, print "Level 2")
    |
    +----B----C---- (pid1==0, pid2!=0, pid3!=0, print nothing)
         |    |
         |    +---- (pid1==0, pid2==0, pid3==0, print nothing)
         |
         +----C---- (pid1==0, pid2==0, pid3!=0, print nothing)
              |
              +---- (pid1==0, pid2==0, pid3==0, print nothing)

理想情况下,下面是我希望看到的解释方式,因为这种方式对我来说很有意义。 * 是我主要的困惑所在。例如,当子进程创建一个包含父进程所有值的进程时,pid1 = fork(); 是否会向父进程 pid1 传递一个值,例如 1?这意味着 child 将有 pid 1=0、pid2=0 和 pid3=0,而 parent 则为 pid1=2 和 pid2 和 3 等于 0? enter image description here

最佳答案

System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, we have to distinguish the parent from the child. This can be done by testing the returned value of fork()

Fork 是一个系统调用,您不应将其视为普通的 C 函数。当发生 fork() 时,您有效地创建了两个具有自己地址空间的新进程。在 fork() 调用之前初始化的变量在两个地址空间中存储相同的值。但是,在任一进程的地址空间内修改的值在其他进程中不受影响,其中一个是父进程,另一个是子进程。 所以如果,

pid=fork();

如果在后续代码块中检查 pid 的值。两个进程都运行整个代码长度。那么我们如何区分它们。 同样,Fork 是一个系统调用,这里有区别。在新创建的子进程中,pid 将存储 0,而在父进程中,它将存储正值。pid 中的负值表示 fork 错误。

当我们测试pid的值时 要确定它是等于零还是大于它,我们实际上是在确定我们是在子进程中还是在父进程中。

Read more about Fork

关于c - C 中的 Fork() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32810981/

相关文章:

C#include pbl.h路径

c - 为什么某些内核操作不能用 C 编写

c - 在以下情况下如何处理解引用运算符

c - 76 个字符长的字符串的单义哈希函数

c - 难以理解 fork() 和进程树

java - 进程间共享线程

linux - 首先查找订单目录,最后查找文件

linux - 如何检测是否从另一个 shell 脚本调用了 shell 脚本

linux - 是否可以对传输到更多的输出进行着色?

c - 上面显示的程序使用 Pthreads API。 LINE C 和 LINE P 处的程序的输出是什么?