Do you know where your variables are? PerlMonks

### Re: strange behaviour when forking lots of times

by davido (Cardinal)
 on May 16, 2006 at 05:22 UTC ( #549668=note: print w/replies, xml ) Need Help??

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

Create A New User
Node Status?
node history
Node Type: note [id://549668]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2020-10-30 17:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My favourite web site is:

Results (282 votes). Check out past polls.

Notices?