Search code examples
cforkhierarchy

Fork() code not working as expected - Hierarchy making


Good afternoon.

I am currently working on a C program that takes one and only one parameter which designates the number of "child generation"s to be created (the own father counts as 1 already). "wait()" system calls are not to be used for this exercise (the version with "wait" calls happens to work exactly as expected).

For instance, the call $program 4 should generate a hierarchy like this: Process A creates B Process B creates C Process C creates D

The printed messages are not important, as they are merely orientative for the task. With the following code (which happens to work exactly how I want with a "wait()" call) states that all the child processes derive from the same father, which I don't understand why it's happening.

#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());
            }
        }
    }

The hierarchy generated by the code above is not the one I expected...

All help is greatly appreciated. Thank you


Solution

  • You are missing a crucial function call.

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

    Without it, your fork duplicates parent's stdout buffer into the child process. This is why you are seeing parent process output repeated several times --- its children and grandchildren inherit the output buffer.

    Live demo (with fixed formatting for your reading convenience).