Doh! Stupid Programming Mistakes <humor>

Doran Barton fozz at iodynamics.com
Thu Oct 19 11:51:05 MDT 2006


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Alex Esplin wrote:
> On 10/19/06, Corey Edwards <tensai at zmonkey.org> wrote:
>> I guess you forked off 10! (3,628,800) processes. We like to call that a
>> fork bomb.
> 
> Eh?  Somebody wanna enlighten a confused young whippersnapper that has
> no clue what is going on here but would like to learn something?

The problem here is a lack of understand of how fork() works.

>    for(x = 0; x < 10; x++){
>     if(fork() > 0){
>         MPI_Comm_rank(MPI_COMM_WORLD, &myrank); /* Get my rank          */
>         MPI_Comm_size(MPI_COMM_WORLD, &size);   /* Get the total number of
> processors */
>         printf("Processor %d of %d: Running!\n", myrank, size);
>     }
>    }
>    MPI_Finalize();                         /* Terminate MPI        */
> } 

What fork() does is it creates a copy of the current running process. The
only difference between the two is the process ID (and parent process ID). As
a programmer, it's your responsibility to code things differently for parent
and child. You can write code for this by using the return value of the
fork() call. If the return value is a 0, the process is the child process. If
the return value is a positive integer, the process is the parent process and
the return value is the child's process ID.

Now that you understand this behavior, look at the code above, the parent
calls fork() 10 times and then exits the loop. Each child, however, has the
same code. The child processes won't enter the if-block (because the return
value of fork() is 0), but they will continue iterating through the for-loop.

The first child (x=0) will fork() 10 times just like the parent. The second
child (x=1) will fork() 9 times. And so on. And each child will be forking
more processes as well.

The solution? An exit() call for the child processes:

   for(x = 0; x < 10; x++){
    if(fork() > 0){
        MPI_Comm_rank(MPI_COMM_WORLD, &myrank); /* Get my rank          */
        MPI_Comm_size(MPI_COMM_WORLD, &size);   /* Get the total number of
processors */
        printf("Processor %d of %d: Running!\n", myrank, size);
    }
    else {
      do_something_useful();
      exit(1);
    }
   }


- --
fozz at iodynamics.com is Doran L. Barton, president/CTO, Iodynamics LLC
Iodynamics: IT and Web services by Linux/Open Source specialists
 "This hotel is renowned for its peace and solitude. In fact, crowds from
  all over the world flock here to enjoy its solitude."
    -- Seen in an Italian hotel brochure
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)
Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org

iD8DBQFFN7sJfSztmbgzr0ERAp4IAJ0WFRPjM9XEQ4FFn0BCOUXnlaBFtwCffMGI
SeYHMHZZjaNLWHBabqSgvXQ=
=bv2o
-----END PGP SIGNATURE-----



More information about the PLUG mailing list