Skip to Main Content

Department of Computer Science

Technical Services and Support

Preventing Fork Bomb on Linux

by Hanz Makmur

Fork bomb is essentially runaway recursive processes. Fork bombs cause user to runs out of resources very quickly. Depending on preset maximum user processes on your system, it can crash the system or prevent the user from continuing any work.
In this document we will treat a thread as a process.  In Linux, processes and threads are almost the same. The major difference is that threads share the same virtual memory address space.
Stopping fork bomb requires termination of all running copies of run away processes and difficult to do especially when the user runs out of processes.
Note: In this page, we assume you are using bash shell. 
Current Maximum Limit
To find out the current maximum processes you can run, type ulimit -u. This will return you a number, for example: 2000. This means you can run maximum of 2000 processes. This number could be different depending on your group membership. To protect your session from a fork bomb, you want to lower that number so your program does not use up all your available processes due to programing mistakes.
Setting a New Maximum Limit
Before you set your maximum process limit, you need to find out how many threads your current session are using, type:  pgrep -wcu $USER  If you are using X2Go or Remote Desktop,  this will return between 325-375 threads.  You need to estimate how deep your program will fork.  For example, if your current  session returns 350 running threads and your program needs to fork about 50 threads, you would need  protect your session from fork bomb with 350 + 50  = 400.
Note: don’t set numbers lower than your current threads count. This will prevent you from continue working.
 To limit your session to 400 processes, use the following command in the terminal window:  ulimit -S -u 400  What it does:
1. This command will limit the number of processes in your current shell session to 400 processes.
2. The -S set the soft limit allowing you to set it back by ulimit -S -u 5000.  Without -S, both soft and hard limit are set. Once the hard limit is set, you have to close that shell to reset it.
Stopping Run Away Program
With a limit set,  to stop a run away process, you  can simply type Control+C to stop your running code.
If this fails, open another terminal window session and type pkill -9 recursiveProgramName