How a Fork Bomb Works

bashforkshell-scriptzsh

  • WARNING DO NOT ATTEMPT TO RUN THIS ON A PRODUCTION MACHINE

In reading the Wikipedia page on the topic I generally follow what's going on with the following code:

:(){ :|:& };:

excerpt of description

The following fork bomb was presented as art in 2002;56
its exact origin is unknown, but it existed on Usenet prior to 2002.
The bomb is executed by pasting the following 13 characters into a
UNIX shell such as bash or zsh. It operates by defining
a function called ':', which calls itself twice, once in the
foreground and once in the background.

However the last bit isn't entirely clear to me. I see the function definition:

:(){ ... }

But what else is going on? Also do other shells such as ksh, csh, and tcsh also suffer the same fate of being able to construct something similar?

Best Answer

This fork bomb always reminds me of the something an AI programming teacher said on one of the first lessons I attended "To understand recursion, first you must understand recursion".

At it's core, this bomb is a recursive function. In essence, you create a function, which calls itself, which calls itself, which calls itself.... until system resources are consumed. In this specific instance, the recursion is amplified by the use of piping the function to itself AND backgrounding it.

I've seen this answered over on StackOverflow, and I think the example given there illustrates it best, just because it's easier to see what it does at a glance (stolen from the link above...)

☃(){ ☃|☃& };☃

Define the bug function ☃() { ... }, the body of which calls itself (the bug function), piping the output to itself (the bug function) ☃|☃, and background the result &. Then, after the function is defined, actually call the bug function, ; ☃.

I note that at least on my Arch VM, the need to background the process is not a requirement to have the same end result, to consume all available process space and render the host b0rked. Actually now I've said that it seems to sometimes terminate the run away process and after a screenful of -bash: fork: Resource temporarily unavailable it will stop with a Terminated (and journalctl shows bash core dumping).

To answer your question about csh/tcsh, neither of those shells support functions, you can only alias. So for those shells you'd have to write a shell script which calls itself recursively.

zsh seems to suffer the same fate (with the same code), does not core dump and causes Arch to give Out of memory: Kill process 216 (zsh) score 0 or sacrifice child., but it still continues to fork. After a while it then states Killed process 162 (systemd-logind) ... (and still continues to have a forking zsh).

Arch doesn't seem to have a pacman version of ksh, so I had to try it on debian instead. ksh objects to : as a function name, but using something - say b() instead seems to have the desired result.

Related Question