Why ulimit doesn't work when run with sudo?
ulimit
is shell/process specific. Skip the sudo
.
$ ulimit -s
8192
$ ulimit -s 16384
$ ulimit -s
16384
Daniel Beck's answer doesn't tell all the truth (in fact it's kinda sleight of hand), and doesn't help people needing to actually do "sudo ulimit".
The problem is that
- ulimit has soft and hard limits
- once you set the hard limit, you need to be superuser to set it back higher
- sudo starts a new shell; when you exit it, you're back to your old ulimit!
Detailed explanation
Daniel's example only works out in a very specific situation (which luckily is the default one).
Counterexample:
$ ulimit -s 8191 # set both hard and soft limits
$ ulimit -s # show current soft limit
8191
$ ulimit -s 16384 # set both hard and soft limits
-bash: ulimit: stack size: cannot modify limit: Operation not permitted
So, you set the limit with ulimit -s
, and that went and set both soft and hard limits. Now you're blocked from setting it higher.
At this point you might think to try sudo
; but it won't work, because of what Daniel wrote.
$ sudo ulimit -s 16384 # maybe with sudo?
$ ulimit -s
8191
$
What happened here is that sudo
started a new shell, where it ran ulimit
; and in THAT shell, the new ulimit was set. But then that shell finished its work, was torn down, and now you're back in your previous shell with its previous ulimit.
Proof:
$ ulimit -s 8191
$ ulimit -s
8191
$ sudo bash
# ulimit -s
8191
# ulimit -s 16384
# ulimit -s # It worked!
16384
# exit
exit
$ ulimit -s # ... but now we're back to the old ulimit.
8191
$
So why exactly did Daniel's example work? Because of ulimit's default hard and soft limits, he could push the soft limit to the hard one. We can do it in slow motion to show the trick:
$ ulimit -Ss # show the Soft limit
8192
$ ulimit -Hs # show the Hard limit
65532
$ ulimit -s # by default, shows the Soft limit
8192
$ ulimit -s 16384 # set both the Soft and Hard limit
$ ulimit -s # shows the Soft limit
16384
$ ulimit -Hs # but, gotcha! the Hard limit has also been set
16384
$ ulimit -s 16385 # so now we can't go higher
-bash: ulimit: stack size: cannot modify limit: Operation not permitted
$
In summary: if you set your hard limit and want to push it up, you're out of luck in that shell, ... unless you stay as superuser or use some incantation to drop privileges afterwards.