strange behaviour with ulimit on Mac OS X 10.6

I get some very strange behaviour when working with ulimit. I just open up a new shell

Hector:~ robertj$ ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
file size               (blocks, -f) unlimited
max locked memory       (kbytes, -l) unlimited
max memory size         (kbytes, -m) unlimited 
open files                      (-n) 256 
pipe size            (512 bytes, -p) 1
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 532
virtual memory          (kbytes, -v) unlimited

Ok, that seems to be the default even thou I set the limit on files within /etc/launchd.conf to be unlimit. But that is another question for another day.

Now I increase the number of files to 1024 and let have a look unto the new settings again.

 Hector:~ robertj$ ulimit -n 1024
 Hector:~ robertj$ ulimit -a | grep open
 open files                      (-n) 1024

Okay, that works. cool! Now lets change the settings again

Hector:~ robertj$ ulimit -n 512
Hector:~ robertj$ ulimit -a | grep open
open files                      (-n) 512

Again that works fine nicely. Lets change again to some higher value

Hector:~ robertj$ ulimit -n 1024
-bash: ulimit: open files: cannot modify limit: Operation not permitted
Hector:~ robertj$ 

What the f*** is this now?

If I try to sudo this I dont get an error but the value doesnt get changed either.

Hector:~ robertj$ sudo ulimit -n 1024
Password:
Hector:~ robertj$ ulimit -a | grep open
open files                      (-n) 512
Hector:~ robertj$ 

What is going on here?

I am completely stumped!

Any help is greatly appreciated...

Robertj


There are two things confusing you. The first is that there are both hard and soft limits for each resource. ulimit -n 512 sets both of them, but ulimit -a only shows the soft limit. Once the hard limit is set, it can only be decreased.

$ ulimit -n
256
$ ulimit -Hn  # There's no initial hard limit
unlimited
$ ulimit -n 512  # This sets both the hard and soft limits
$ ulimit -n
512
$ ulimit -Hn
512
$ ulimit -n 1024  # Once set, the hard limit cannot be increased
-bash: ulimit: open files: cannot modify limit: Operation not permitted

The second thing that's confusing you is that sudo ulimit doesn't do what you think it does. It spawns a (root) subprocess, sets the open file limits for that subprocess, and then exits the subprocess. The limits are a per-process setting, so sudo'ing a change to them doesn't do anything useful.