Home > Back-end >  fork() - Child code is called multiple times (same PID)
fork() - Child code is called multiple times (same PID)

Time:04-29

As an excersise, I wrote a C program that handles Signals and counts them etc. The program itself is actually "working" as intended, however:

The program uses fork() several times, creating a single child first, which in turn then forks two more children (i.e. grandchildren of the top-level parent). The top-level parent waits for the child to finish, and before that, the child waits for its children to finish.

Trying to understand what's going on I printed a little debug message everytime the child code executes (to make sure its only executing once - as intended).

This is what I get though:

Note: Child PID: 28411
Note: Grandchild 2 PID: 28413
Note: Child PID: 28411
Note: Grandchild 1 PID: 28412
Note: Child PID: 28411

Grandchild with PID 28413 called SIGUSR2 1139226 times
Grandchild with PID 28412 called SIGUSR1 1140378 times

Print to console successful
All done!
[Done] exited with code=0 in 5.493 seconds

The first child call is correct, the grandchildren are fine as well. However, the child code, for some reason, is executed two more times. Its also not a new process, since the PID is the same.

This is how I fork the child:

pid_t child = fork();

    if (child == -1) {
        perror("Failure to fork in main\n");
        exit(-1);
    }
    else if (child == 0) {
        childCode();
    }
    else {
        wait(NULL);
    }

And this is how I fork the grandchildren:

pid_t grandchild1 = fork();

    if (grandchild1 == -1) {
        // Error
        perror("Failure to fork first grandchild");
    }
    else if (grandchild1 == 0) 
        // Grandchild
        grandchildCode(1); 
    else {
        // Child 
        pid_t grandchild2 = fork();

        if (grandchild2 == -1) {
            // Error
            perror("Failure to fork second grandchild");
            exit(-1);
        }
        else if (grandchild2 == 0) {
            // Grandchild 
            grandchildCode(2);
        }
        else {
            // Child
            wait(NULL);
        }
    }

Because I dont want to clutter this thread with useless code, here is the full program on Pastebin: https://pastebin.com/XnZEaaNZ (or should I include it here?)

I would be very thankful for any information on this. I can't figure it out.

CodePudding user response:

The output suggests the flow is working exactly as you expect, the problem seems to be with the output itself, stdout is not being flushed in time before the next fork is called and will be passed to the children which will then print the text, as expected since it's in their stdout.

This can be resolved if you place a fflush(stdout) after the printf calls.

  •  Tags:  
  • c
  • Related