Skip to Main Content

Department of Computer Science

Technical Services and Support

Preventing Fork Bomb on Linux

by Hanz Makmur 

A fork bomb is a runaway recursive process. Fork bombs cause users to run out of resources very quickly. Depending on your system’s preset maximum user processes, it can crash 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 terminating all running copies of runaway processes and is difficult to do, especially when the user runs out of processes.
 
Note: We assume you are using a bash shell on this page. 
 
Current Maximum Limit
To determine the current maximum processes you can run, type ulimit -u. This will return you a number, for example, 2000. This means you can run a 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 programming mistakes.
 
Setting a New Maximum Limit
Before you set your maximum process limit, you need to find out how many threads your current session is using; type pgrep -wcu $USER. If you are using X2Go or Remote Desktop,  this will return between 325 and 375 threads.  It would be best if you estimated 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 must protect your session from a fork bomb with 350 + 50  = 400.
 
Note: Don’t set numbers lower than your current thread 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 shell session to 400.
2. The -S sets the soft limit, allowing you to set it back by ulimit -S -u 5000.  Without -S, both soft and hard limits are set. Once the hard limit is set, you must close that shell to reset it.
 
Stopping Run Away Program
With a limit set,  to stop a runaway process, you can type Control+C to stop your running code.
If this fails, open another terminal window session and type pkill -9 recursiveProgramName