Things to Remember when Using ulimit

On Linux, ulimit allows you to limit the resources that a process can use. Two use cases:

  1. You have a program that sometimes runs out of memory, slowing your computer down to a crawl. You can use ulimit -v to limit the amount of memory that processes in a shell can use. If a process tries to allocate more memory than that, the allocation will fail and the program will usually abort.
  2. You have a program with a deep recursion, which segfaults with the default stack limit of 8M. You can use ulimit -s to increase the allowed stack size.

There are many more limits you can set; type help ulimit in bash to list them. You can find out the current limits by typing ulimit -a.

Two gotchas that I always forget about:

  1. You may try to limit the memory usage of a process by setting the maximum resident set size (ulimit -m). This has no effect on Linux. man setrlimit says it used to work only in ancient versions. You should limit the maximum amount of virtual memory (ulimit -v) instead.
  2. ulimit has hard limits and soft limits. Hard limits can be decreased but not increased. You can shoot yourself in the foot if you set your hard limit too low. I recommend using soft limits only. Set them with, for example, ulimit -Sv, and query them with ulimit -Sa.

Happy hacking!