void sanitize_file_descriptors()

in xar/XarExecFuse.cpp [166:189]


void sanitize_file_descriptors() {
  // Close all fds that aren't 0, 1, 2.
  tools::xar::close_non_std_fds();

  // Replace fd 0, 1, and 2 with reasonable /dev/null descriptors if
  // they aren't already open.  Since open always returns the lowest
  // unopened fd, we can just open and refuse to close if the fd is
  // what we want.
  int in_fd = open("/dev/null", O_RDONLY);
  XAR_PCHECK_SIMPLE(in_fd >= 0);
  if (in_fd > 0) {
    close(in_fd);
  }

  // Fill fd 1 and 2 with /dev/null if they're not already open.
  while (true) {
    int out_fd = open("/dev/null", O_WRONLY);
    XAR_PCHECK_SIMPLE(out_fd >= 0);
    if (out_fd > 2) {
      close(out_fd);
      break;
    }
  }
}