0

I haven't really figured out yet how fork() actually works. I wonder how I can make a parent process with for example multiple children?

fork();
fork();

will this return a parent with two children? first fork() = parent + child, second fork() = idk?

Clifford
  • 88,407
  • 13
  • 85
  • 165
sdasd
  • 3
  • 1
  • 2

3 Answers3

3

fork() splits the current program, making two identical copies - the difference is only in the return code of the fork().

So if you fork() twice:

 fork();
 fork();

Then what will happen is - the first fork will split parent into parent + child.

The second fork will split both, because the child carries on from the same point. Giving you:

parent 
+ - child
  + - child
+ - child

To avoid this, you need to check the return code of fork() and use the return code to decide if you're still in the parent. It's not necessarily a bad thing, but you need to be aware that it'll happen, and ensure you handle e.g. signals, return codes, waitpids etc. appropriately. So normally you'll do the forking from just the parent.

Sobrique
  • 52,974
  • 7
  • 60
  • 101
2

It will make a total of 4 processes.

The main process will fork one with the first fork();

At the second fork();, both of the previous ones will create new processes which does make 2x2=4.

antonio
  • 722
  • 11
  • 22
2

fork() returns a process id of a child process to the parent or zero to the child. So:

if( fork() != 0)  // create a child
{
    // we are in parent
    if( fork() != 0)  // create another child
    {
        // we are in parent
    }
    else
    {
        // we are in the 2nd child
    }
}
else
{
    // we are in the 1st child
}

You can also create a child process from a child process:

if( fork() != 0)  // create a child
{
    // we are in parent
}
else
{
    // we are in the child
    if( fork() != 0)  // create a grand-child
    {
        // we are in a first child
    }
    else
    {
        // we are in the grand-child
    }
}

To create 5 children:

// describe the work for 5 children
SomeWorkDescription tab[ 5 ];

int  childCnt;

for( childCnt = 0; childCnt < 5; childCnt ++ )
{
    if( fork() == 0 )
    {
        // we are in a child - take a description
        // of what should be done and go
        doSomeChildWork( tab[childCnt] );

        // it's the parent's loop, children do not iterate here
        break;
    }
    // else we are in a parent - continue forking
}
CiaPan
  • 9,381
  • 2
  • 21
  • 35
  • Gives a solution, but does not directly answer the question about the code the OP posted. – Chnossos Feb 04 '15 at 00:24
  • Yes, it does. The question was _'I wonder how I can make a parent process with for example multiple children?'_ The example shows how s/he can. – CiaPan Feb 04 '15 at 06:03