*BSD News Article 44549


Return to BSD News archive

Path: sserve!newshost.anu.edu.au!harbinger.cc.monash.edu.au!news.uwa.edu.au!classic.iinet.com.au!news.uoknor.edu!news.ecn.uoknor.edu!paladin.american.edu!jhunix1.hcf.jhu.edu!cambot.res.jhu.edu!jelson
From: jelson@cambot.res.jhu.edu (Jeremy Elson)
Newsgroups: comp.unix.bsd.netbsd.misc
Subject: How do I find the max number of open files?
Date: 24 May 1995 18:55:25 GMT
Organization: Johns Hopkins University
Lines: 69
Message-ID: <3pvvet$6a9@jhunix1.hcf.jhu.edu>
Reply-To: jelson@jhu.edu
NNTP-Posting-Host: 128.220.39.20


Hi,

I maintain a piece of software designed to be portable across many UNIX
platforms.  One of the things my software needs to know is the maximum
number of files the process is allowed to have open at once.  Here is the
code I've been using:


int get_avail_descs(void)
{
  int max_descs = 0;

/*
 * First, we'll try using getrlimit/setrlimit.  This will probably work
 * on most systems.
 */
#if defined (RLIMIT_NOFILE) || defined (RLIMIT_OFILE)
#if !defined(RLIMIT_NOFILE)
#define RLIMIT_NOFILE RLIMIT_OFILE
#endif
  {
    struct rlimit limit;

    getrlimit(RLIMIT_NOFILE, &limit);
    max_descs = MIN(MAX_PLAYERS + NUM_RESERVED_DESCS, limit.rlim_max);
    limit.rlim_cur = max_descs;
    setrlimit(RLIMIT_NOFILE, &limit);
  }
#elif defined (OPEN_MAX) || defined(FOPEN_MAX)
#if !defined(OPEN_MAX)
#define OPEN_MAX FOPEN_MAX
#endif
  max_descs = OPEN_MAX;         /* Uh oh.. rlimit didn't work, but we have
                                 * OPEN_MAX */
#else
  /*
   * Okay, you don't have getrlimit() and you don't have OPEN_MAX.  Time to
   * use the POSIX sysconf() function.  (See Stevens' _Advanced Programming
   * in the UNIX Environment_).
   */
  errno = 0;
  if ((max_descs = sysconf(_SC_OPEN_MAX)) < 0) {
    if (errno == 0)
      max_descs = MAX_PLAYERS + NUM_RESERVED_DESCS;
    else {
      perror("Error calling sysconf");
      exit(1);
    }
  }
#endif

  return max_descs;
}


This tries, in order, to use getrlimit (first testing whether or not it's
available by checking to see if RLIMIT_NOFILE is defined), then tries to
see if OPEN_MAX has been defined, then uses the POSIX sysconf() function.

I don't have access to a NetBSD system so I can't figure this out for myself,
but users who use NetBSD have reported that this function returns 0.  My
question: why?  I don't even know which of the three clauses is generating
the 0, unfortunately.

Thanks for any light you may be able to shed on this.

Jeremy
jelson@jhu.edu