File Descriptors
-
To summarize, in Unix almost all I/O is done on file descriptors, also known as file handles.
-
These file descriptors are implemented as small, non-negative integers, which is the reason why almost all syscalls having to do with I/O take an
intas an argument. -
by using a file descriptor, the syscall in question does not need to know whether it actually represents an actual file, a pipe, or a socket, for example.
-
-
stdin, stdout, and stderr are nearly universally declared as 0, 1, and 2, respectively
- we do not use magic numbers in our code and instead use the symbolic definitions for them.
- stdin and stderr are both connected to the terminal by default, so there doesn't seem to be much of a difference between the two, but the elegance of this simple setup becomes apparent when we consider the common use case of piping output from one command into another.
- each program has its stderr connected to the terminal, but stdout and stdin are connected via the pipe, allowing the flow of bytes from one to the other, while each program retains the capability of generating error messages to the terminal.
Question
-
as a multi-processing multi-user system, there always exists the threat of resource starvation of one process (or the entire system) by another. So what is the maximum number of file descriptors a process is allowed to handle? Or, asked another way, how many files is a process allowed to open?
- OPEN_MAX
- getconf(1)
- sysconf(3), _SC_OPEN_MAX
- getdtablesize
- getrlimit(2)
- ulimit -n
-
the maximum number of open files per process is configurable at runtime, meaning it can change from one moment to the next, which is why the sysconf(3) function allows you to retrieve it equally at runtime instead of looking up a fixed constant from a header file.
-
different operating systems may both have different runtime configurations as well as different fixed constants.
-
each process had a fixed size descriptor table, and getdtablesize(3) would return that fixed value. But since the table is dynamic nowadays, this doesn't make much sense.