Fork()代码无法按预期工作-层次结构制作

问题描述 投票:0回答:2

下午好。

我目前正在C语言程序上工作,该C语言程序仅接受一个参数,该参数指定要创建的“子代”的数量(自己的父亲已经计为1)。本练习不使用“ wait()”系统调用(带有“ wait”调用的版本恰好按预期工作)。

例如,调用$ program 4应该生成这样的层次结构:流程A创建B流程B创建C进程C创建D

打印的消息并不重要,因为它们仅针对任务。使用以下代码(通过“ wait()”调用恰好可以正常工作)表明所有子进程均来自同一父进程,而我不知道为什么会这样。

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

    int main(int argc, char *argv[]) {
    int counter; pid_t result; int i;

    /*
    We are going to create as many processes as indicated in argv[1] taking into account that the main father already counts as 1!
    */
    if (argc > 2 || argc == 1) {puts("IMPOSSIBLE EXECUTION\n"); exit(-1);}
    int lim = atoi(argv[1]);


    //We eliminate the impossible cases
    if (lim < 1) {puts("IMPOSSIBLE EXECUTION\n"); exit(-1);}


    if (lim == 1) {puts("The father himself constitutes a process all by his own, therefore:\n");
    printf("Process%d, I'm %d and my father: %d\n", counter, getpid(), getppid());
     }
    else {
        for (i = 0; i < lim; i++) {
            result = fork();
            if (result < 0) {
                printf("Call%d \n", counter); perror("Has failed!");
                exit(-1);
            }
            else if (result) {
                break; //Father process
            }
            else {
                counter++;    //Child processes increment the counter
                printf("Process%d, I am %d and my father: %d\n", counter, getpid(), getppid());
            }
        }
    }

上面的代码生成的层次结构不是我期望的层次结构...

非常感谢所有帮助。谢谢

c fork hierarchy
2个回答
0
投票

您缺少关键的函数调用。

    for (i = 0; i < lim; i++) {
        fflush(stdout);             // <============== here
        result = fork();

没有它,您的fork将父级的stdout缓冲区复制到子进程中。这就是为什么您看到父进程输出重复多次的原因---它的子级和子级继承了输出缓冲区。

[Live demo(具有固定格式以便您阅读)。>


1
投票

使用以下代码(它恰好可以按照我的意愿工作“ wait()”调用)指出所有子进程都从同一个父亲,我不明白为什么会这样。

© www.soinside.com 2019 - 2024. All rights reserved.