c - c程序中的多个fork()

标签 c linux process fork

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
    pid_t pid1, pid2, pid3, pid4;
    pid1=fork();

    if (pid1!=0) {
        pid2=fork();
        pid3=fork(); 
    }else { 
        pid4=fork(); 
    } 
    return 0;
}

您好, 以下代码执行 4 个 fork 。首先,原始进程(我们称之为 P0)执行“pid1=fork()”并创建一个子进程(我们称之为 P1)。然后原始进程再次执行 pid2=fork() 并创建另一个子进程(我们称之为 P2)。然后P2和P0都执行“pid3=fork()”。所以 P0 创建了第三个 child (称为 P3),P2 成为父节点并创建了一个 child (称为 P4)。最后,在 else 语句中,第一个 child (P1)创建了一个 child (P5)。所以这棵树就像:

                  P0
              P1   P2   P3
            P5      P4

我的问题是:我说得对不对? 提前致谢。

最佳答案

My question is: Am i right or not?

是的。

正如 Paul R 在评论中所说,尝试放入一些 printf。例如在

pid1 = fork()

尝试放置

printf("pid %d: pid1 = fork(), result = %d\n", getpid(), pid1);

getpid() 获取当前进程的pid。

关于c - c程序中的多个fork(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43326857/

相关文章:

c - 在 C 中为函数计时

c - 用于自定义信号处理程序的退出代码的最佳实践?

linux - Git 还原有其他依赖于它的提交的提交

c - 是否可以多次调用 waitpid ? [UNIX] [C]

process - 是否有一种面向描述代理之间交互的编程语言?

c - 如何找到数组的大小(从指向数组第一个元素的指针)?

c - Pthread 服务器编程 : how to release a thread which is blocked on a recv call to handle a request from another thread

c - c中的字符串指针

c - Linux中自动启动应用程序,输出失败

c - 在没有新线程的情况下替换无限循环