Search code examples
cfile-descriptor

Best way for checking 0, 1, 2 file descriptors vs ISC solution


In ISC source code on server directory and dhcpd project we have following codes for checking 0, 1, 2 file descriptors.

code:

  /* Make sure that file descriptors 0 (stdin), 1, (stdout), and
     2 (stderr) are open. To do this, we assume that when we
     open a file the lowest available file descriptor is used. */
  fd = open ("/dev/null", O_RDWR);
  if (fd == 0)
    fd = open ("/dev/null", O_RDWR);
  if (fd == 1)
    fd = open ("/dev/null", O_RDWR);
  if (fd == 2)
    log_perror = 0; /* No sense logging to /dev/null. */
  else if (fd != -1)
    close (fd);

I can't understand what doe's this code works.

It opened /dev/null and compare its fd number with 0.

But why it opened new fd from the same /dev/null or rather that same file ?

I tested this code :

  int fd = open ("/dev/null", O_RDWR);

  printf ("fd: %d\n", fd);

In this code output equal to 3 but why ?

If this fd always equal to 3, then what will happen ?


Solution

  • The code does exactly what it says.

    Make sure that file descriptors 0 (stdin), 1, (stdout), and 2 (stderr) are open. To do this, we assume that when we open a file the lowest available file descriptor is used.

    It tries opening a file; if its fd is 0 (stdin), it's assumed no stdin handle had been opened. If so, it continues to open fd 1 (stdout) and fd 2 (stderr). Finally, if it had opened fd 2 (stderr), it can know it's /dev/null and there's no point wasting cycles writing there, and sets the flag accordingly.

    Finally, if the fds the code opened weren't 0, 1, or 2, the fd is closed to avoid leaking an fd that's not used.

    I tested this code : [...]

    Because in that case, stdin, stdout, and stderr were already open and you got fd 3.