user1508893
user1508893

Reputation: 9813

creating child processes in parallel

Say I have this piece of code

for (int n = 0; n < 4; ++n)
{
   if (fork())
   {
      // do something
      // if some condition is met
      // kill the parent
      // else, just return 
   }
   else
      printf("cannot get a process\n");
}

Would I be creating 4 child-processes running in parallel? Or would I be creating 4 of them running one after the other (because the loop in the parent won't advance until the child-process returns) ?

Thank you

P.S: I do realise this might be a bad practice (ie., killing the parent from a child causes zombies to go around, but let's ignore that for now!).

Upvotes: 0

Views: 11787

Answers (1)

William Pursell
William Pursell

Reputation: 212514

Re-writing your code as:

for( int n = 0; n < 4; ++n ) {
    switch( fork()) { 
        case 0: /* child */
            /* Do stuff */
            exit( 0 );
        case -1:
            perror( "fork" );
            exit( 1 );
        default:  /* parent */
            /* do stuff, but don't wait() or terminate */
    } 
}

The children will indeed run in parallel. Although it is entirely possible that one child will run quickly and terminate before the next runs, in which case the children are effectively running serially. If the parent waits on a child, they will run serially. Also, note that if the parent does not wait() here, and does not wait outside the loop, the children will become zombies when they terminate. As soon as the parent terminates, the zombie children will be inherited by init, which will wait on them and remove them from the process table (so they will cease to be zombies.)

Upvotes: 2

Related Questions