Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 257
mimoralea Avatar asked Jun 06 '12 06:06

mimoralea


People also ask

How many child process will be created with 2 fork () calls?

Fork #2 is executed by two processes, creating two processes, for a total of four.

How many child processes are created using fork ()?

So there are total eight processes (new child processes and one original process).

Does fork () create a child?

The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call.


1 Answers

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
like image 194
tuxuday Avatar answered Sep 21 '22 09:09

tuxuday