C 帮助创建进程树

标签 c fork

我正在尝试创建一个进程树,但这是我现在的输出:https://gyazo.com/a71f4e095b69080a6d6a11edd2c0df27 问题是我想让它看起来像我在右边画的图,但似乎不知道如何做。我正在打印每个子进程的父 ID,然后在执行此操作后,我将从 2 开始删除它们,然后从 1 开始(通过在 5 秒后发送 SIGKILL 信号)。 如何使流程树看起来像所需的结果?这是我的代码:

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


int main()
{
    int root, t1, t2, i;

    root = getpid();
    printf("root %d\n", root);
    for (i = 1; i < 3; i++)
    {
        t1 = fork();
        //printf("%d\n", t1);
        if(t1!=0)
        {
        t2 = fork();
        }
        if (t1 !=0 && t2 != 0)
        {
            break;
        }

        printf("child pid %d    parent pid %d\n", getpid(), getppid());
    }
    sleep(10);

    return 0;
}

谢谢!

最佳答案

您的主 for 循环在所有分支中运行,这与您的图表不匹配。 您真正想要的是 if 语句与树具有相同的结构:

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


int main()
{
    printf("root %d\n", getpid());

    if (fork())
    {
        fork();
    } else {
        if (fork())
        {
            if (fork())
            {
                fork();
            }
        }
    }

    printf("child pid %d    parent pid %d\n", getpid(), getppid());

    fflush(stdout);

    sleep(10);

    return 0;
}

这给出了期望的结果:

root 5140
child pid 5140    parent pid 377
child pid 5147    parent pid 5141
child pid 5149    parent pid 5141
child pid 5146    parent pid 5140
child pid 5148    parent pid 5141
child pid 5141    parent pid 5140

注意。 sleep() 是为了确保没有任何进程在它们的子进程之前退出,此时它们的子进程将被重新设置为 ppid = 1 (init)。

关于C 帮助创建进程树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46437461/

相关文章:

assembly - Macos 64 位程序集 - fork() test/jne 不起作用?

Linux Fork 的目的?

c - C execve() 函数是否终止子进程?

c - 由于 SSE 指令未对齐内存访问而导致的一般保护异常

c++ - CUDA C - 从 cutil.h 到 helper_cuda.h 的库错误

javascript - 在 Python 或 JavaScript 中实现 C 预处理器?

c - 为什么下面的语句打印三次?

c - 用户输入未被识别,但如果最初设置了数字则程序可以运行

python - 读取没有 EOF 标志的文件

c++ - c/c++ 中的线程程序是否应该比串行程序运行得更快?