Fork bombs and creating more than one child

Say we want to write code to create three children; would this, the code shown as follows, do it?

main() {    [...]    fork();    fork();    fork();    [...]}

Of course not! (try it and see).

Recall fork rule #1: Execution in both the parent and child process continues at the instruction following the fork. Thus, as you can see, after the first fork, both the parent and child run the second fork (so we'll now have a total of four processes), and then all four will run the third fork (giving us a total of eight processes), and so on (havoc!).

If fork is called in this uncontrolled manner—it ends up creating 2^3 = 8 children! In other words, it's exponential; n forks implies 2^n children will be created in a runaway ...

Get Hands-On System Programming with Linux now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.