http://www.perlmonks.org?node_id=549668


in reply to strange behaviour when forking lots of times

What you are learning with this simple Perl program is that if you fork 10! (ten factorial) times, and you're lucky enough for your system to still be running, you get odd behavior. For the record, 10! (ten factorial) means you're spawning a total of 3628800 child processes (three million, six hundred twenty eight thousand, eight hundred).

The immediate lesson learned should be "Don't do that." And the "big picture" lesson learned should be "Be careful when using fork, that you don't unwittingly create a fork bomb."

The disasterous magic here is that each forked process inherits the remainder of the loop. So ten processes are spawned, each of whom spawn nine processes, each of whom spawn eight, and each of those spawn seven... and so on.

10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 10! = 3628800. Wow!


Dave

  • Comment on Re: strange behaviour when forking lots of times

Replies are listed 'Best First'.
Re^2: strange behaviour when forking lots of times (1<<$N)
by tye (Sage) on May 16, 2006 at 15:13 UTC

    No, it forks about 2**11 processes. The first time through the loop, it forks once, creating two processes that each have 9 items left to do. The next time, the 2 processes become 4 that each have 8 items left to do. Then 4 become 8 that each have 7 items left to do... For a total of 2*(2**$N-1). And the whole run takes a fraction of second. (:

    - tye