RichardLiu
RichardLiu

Reputation: 1952

Is the value of a Linux file descriptor always smaller than the open file limits?

Is the "value" of a Linux file descriptor always smaller the open file limits ?

Theoretically, the system shall re-use the identity values of closed file descriptors. And I should get file descriptor values ranged from 0,1,2 up to 1023 by default, after opened 1021 files in one process. If I want to open another file, I have to release some file descriptors with close, and system shall re-use these released identities when I call open again. So the maximum integer value of a file descriptor should be 1023 in this case. Is that correct ?

I know that I can change the open file limits with ulimit -n, setrlimit, and /proc/sys/fs/file-max. I just want to know whether I can store an opened socket file descriptor with a char variable, if I had reduced the open file limits to 128 with setrlimit.

Upvotes: 1

Views: 1814

Answers (1)

Douglas B. Staple
Douglas B. Staple

Reputation: 10946

Yes, the values are limited to the range from 0 to one less than the current limit as returned by getrlimit().

From the getrlimit() man page:

   RLIMIT_NOFILE
          Specifies a value one greater than the maximum file descriptor number
          that can be opened by this process.  Attempts (open(2), pipe(2),
          dup(2), etc.)  to exceed this limit yield the error EMFILE.
          (Historically, this limit was named RLIMIT_OFILE on BSD.)

From the Open Group Base Specification:

RLIMIT_NOFILE
This is a number one greater than the maximum value that the system may assign to a newly-created descriptor. If this limit is exceeded, functions that allocate a file descriptor shall fail with errno set to [EMFILE]. This limit constrains the number of file descriptors that a process may allocate.

Upvotes: 3

Related Questions