Search code examples
cfile-descriptor

Why 20 is omitted from the file descriptor


EDIT:

lsof shows that it's opened by ptmx. Thanks to @zwol


My code below prints the file descriptor returned from open. I noticed that 20 is missing. There is no similar question to the best of my knowledge.

background:

  • Filesystem: ext4
  • Ubuntu 20.04 on WSL2

code:

int main()
{
    char name[2] = "a";
    for (int i = 0; i < 52; i++) {
        int fd = open(name, O_RDWR | O_CREAT, 0644);
        printf("fd is %d\n", fd);
    }
    return 0;
}

output:

$ ./a.out 
fd is 3
fd is 4
fd is 5
...
fd is 18
fd is 19
fd is 21 <-- here
fd is 22
...

lsof

...
a.out   1815 ryan   19u   REG   8,16        0 42321 /tmp/tmp/a
a.out   1815 ryan   20u   CHR    5,2      0t0 15832 /dev/ptmx
a.out   1815 ryan   21u   REG   8,16        0 42321 /tmp/tmp/a
...

I have 2 questions:

  1. What's the reason behind it? (What triggers ptmx)
  2. Will there be more indices missing if I keep opening files? (More programs like ptmx?)

Solution

  • POSIX says that every system call that allocates file descriptors must use the lowest number(s) that are not already in use. Therefore, descriptor number 20 must have already been open. Your sample program doesn't open anything before the loop, so it must have been inherited from your shell, or opened by the C library prior to main.

    You can find out more by having your program print its PID and then sleep for a long time, after the loop, and then running lsof on it while it's sleeping.