How to use Fork() to create only 2 child processes?

mimoralea picture mimoralea · Jun 6, 2012 · Viewed 78.2k times · Source

I'm starting to learn some C and while studying the fork, wait functions I got to a unexpected output. At least for me.

Is there any way to create only 2 child processes from the parent?

Here my code:

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

int main ()
{
    /* Create the pipe */
    int fd [2];
    pipe(fd);

    pid_t pid;
    pid_t pidb;


    pid = fork ();
    pidb = fork ();

    if (pid < 0)
    {
        printf ("Fork Failed\n");
        return -1;
    }
    else if (pid == 0)
    {
        //printf("I'm the child\n");
    }
    else 
    {
        //printf("I'm the parent\n");
    }

    printf("I'm pid %d\n",getpid());

    return 0;
}

And Here is my output:

I'm pid 6763
I'm pid 6765
I'm pid 6764
I'm pid 6766

Please, ignore the pipe part, I haven't gotten that far yet. I'm just trying to create only 2 child processes so I expect 3 "I'm pid ..." outputs only 1 for the parent which I will make wait and 2 child processes that will communicate through a pipe.

Let me know if you see where my error is.

Answer

tuxuday picture tuxuday · Jun 6, 2012
pid = fork (); #1
pidb = fork (); #2

Let us assume the parent process id is 100, the first fork creates another process 101. Now both 100 & 101 continue execution after #1, so they execute second fork. pid 100 reaches #2 creating another process 102. pid 101 reaches #2 creating another process 103. So we end up with 4 processes.

What you should do is something like this.

if(fork()) # parent
    if(fork()) #parent
    else # child2
else #child1