To determine the maximum number of files your application can open, there is a function getrlimit() available.

  • Easily preview Mermaid diagrams
  • Live update when editing in your preferred editor
  • Capture screenshots with customizable margins
  • Create PNG from the Terminal
  • Free download on the Mac App Store
MarkChart

Here is what tells us the man page:

int getrlimit(int resource, struct rlimit *rlp);

A resource limit is specified as a soft limit and a hard limit.
When a soft limit is exceeded a process may receive a signal (for example, if the cpu time or file size is exceeded),
but it will be allowed to continue execution until it reaches the hard limit (or modifies its resource limit).
The rlimit structure  is used to specify the hard and soft limits on a resource,

struct rlimit {
	rlim_t  rlim_cur;       /* current (soft) limit */
	rlim_t  rlim_max;       /* hard limit */
};

Let’s create an application to print the soft and hard limit. I simply created a new Cocoa project and add this awakeFromNib function:

#include <stdio.h>
#include <sys/resource.h>
 
-(void)awakeFromNib
{
     struct rlimit lim;
     int theErr = getrlimit(RLIMIT_NOFILE, &lim);
     if(theErr == 0)
     {
        if(lim.rlim_max == RLIM_INFINITY)
           fprintf(stderr, "soft: %llu ; hard: RLIM_INFINITY\n", lim.rlim_cur);
        else
            fprintf(stderr, "soft: %llu ; hard: %llu\n", lim.rlim_cur, lim.rlim_max);
     }
     else
     {
         fprintf(stderr, "getrlimit returned an error %d\n", theErr);
     }
}

What would you expect? 256? 512? 1024? More?

Well the value depends on how you run the application! Here are the results on 10.5.8 i386:

  • If you run the application by double clicking on the icon in the Finder:

soft: 256 ; hard: RLIM_INFINITY

  • If you run the application from the terminal:

soft: 256 ; hard: RLIM_INFINITY

  • If you run the application from Xcode without gdb:

soft: 2560 ; hard: RLIM_INFINITY

  • If you run the application from Xcode with gdb:

soft: 10240 ; hard: RLIM_INFINITY

  • If you run the application from the Terminal in gdb:

soft: 10240 ; hard: RLIM_INFINITY

  • If you run a slightly modified application from the Finder and attach it to gdb and call manually the function:

soft: 256 ; hard: RLIM_INFINITY

This is quite confusing! I made a bug report: radar://7123983