diff --git a/src/node.cc b/src/node.cc index 2891c18bb9aa9a..27b770b72385ee 100644 --- a/src/node.cc +++ b/src/node.cc @@ -608,11 +608,20 @@ static void PlatformInit(ProcessInitializationFlags::Flags flags) { for (auto& s : stdio) { const int fd = &s - stdio; if (fstat(fd, &s.stat) == 0) continue; + // Anything but EBADF means something is seriously wrong. We don't // have to special-case EINTR, fstat() is not interruptible. if (errno != EBADF) ABORT(); - if (fd != open("/dev/null", O_RDWR)) ABORT(); - if (fstat(fd, &s.stat) != 0) ABORT(); + + // If EBADF (file descriptor doesn't exist), open /dev/null and duplicate + // its file descriptor to the invalid file descriptor. Make sure *that* + // file descriptor is valid. + const int null_fd = open("/dev/null", O_RDWR); + if (null_fd == fd) continue; + if (dup2(null_fd, fd) != 0) ABORT(); + + if (fstat(fd, &s.stat) == 0) continue; + ABORT(); } }