Difference between ulimit -n and /proc/$PID/limits

limit

In Linux, there is open file limit. I can use ulimit -n to see open file limit, which is 1024 default. Then I also can see per process open file soft/hard limit by looking at /proc/$PID/limits. I see soft = 1024 and hard = 4096.

I am wondering what is the difference between these two output?

Also, do setRlimit() and getRlimit() apply to system-wide or per process?

Best Answer

ulimit -n sets the soft limit by default; you can add the -H option to view/set the hard limit.

For the most part, soft and hard limits behave like this:

  1. root's processes (actually, any process with CAP_SYS_RESOURCE) may raise or lower any limit on any process.
  2. any user's processes may lower any limit on other processes owned by that user.
  3. any user's processes may raise the soft limit up to the hard limit on processes owned by that user.
  4. If a process attempts to exceed its soft limit, the attempt will fail.

So, hard limits function as a cap on soft limits (except for root, who as normal can do anything).

There is an exception: A soft CPU limit sends a SIGXCPU signal. A process may choose to ignore that, or spend time doing cleanup, etc. Once the hard CPU limit is crossed, the kernel sends SIGKILL—which is not catchable, handleable, or ignorable. So in this case, the soft limit functions as a warning "you're out of CPU time—finish up and exit promptly, or else!" and the hard limit is the "or else."

Most are per-process, but a few (such as RLIMIT_NPROC) are per user. The getrlimit(2) manual page specifies for each limit.

Related Question