diff --git a/src/io/file_descriptor.cr b/src/io/file_descriptor.cr index 30ad23f5e192..a73b5fdbc26a 100644 --- a/src/io/file_descriptor.cr +++ b/src/io/file_descriptor.cr @@ -20,19 +20,18 @@ class IO::FileDescriptor < IO # :nodoc: def self.from_stdio(fd) - # If we have a TTY for stdin/out/err, it is a shared terminal. + # If we have a TTY for stdin/out/err, it is possibly a shared terminal. # We need to reopen it to use O_NONBLOCK without causing other programs to break # Figure out the terminal TTY name. If ttyname fails we have a non-tty, or something strange. path = uninitialized UInt8[256] - if LibC.ttyname_r(fd, path, 256) == 0 - # Open a fresh handle to the TTY - fd = LibC.open(path, LibC::O_RDWR) + ret = LibC.ttyname_r(fd, path, 256) + return new(fd, blocking: true) unless ret == 0 - new(fd).tap(&.close_on_exec = true) - else - new(fd, blocking: true) - end + clone_fd = LibC.open(path, LibC::O_RDWR) + return new(fd, blocking: true) if clone_fd == -1 + + new(clone_fd).tap(&.close_on_exec = true) end def blocking