Ruby on Linux PTY goes away without EOF, raises Errno::EIO
So I had to go as far as reading the C source for the PTY library to get really satisfied with what is going on here.
The Ruby PTY doc doesn't really say what the comments in the source code say.
My solution was to put together a wrapper method and to call that from my script where needed. I've also boxed into the method waiting on the process to for sure exit and the accessing of the exit status from $?
:
# file: lib/safe_pty.rb
require 'pty'
module SafePty
def self.spawn command, &block
PTY.spawn(command) do |r,w,p|
begin
yield r,w,p
rescue Errno::EIO
ensure
Process.wait p
end
end
$?.exitstatus
end
end
This is used basically the same as PTY.spawn:
require 'safe_pty'
exit_status = SafePty.spawn(command) do |r,w,pid|
until r.eof? do
logger.debug r.readline
end
end
#test exit_status for zeroness
I was more than a little frustrated to find out that this is a valid response, as it was completely undocumented on ruby-doc.
It seems valid for Errno::EIO to be raised here (it simply means the child process has finished and closed the stream), so you should expect that and catch it.
For example, see the selected answer in Continuously read from STDOUT of external process in Ruby and http://www.shanison.com/2010/09/11/ptychildexited-exception-and-ptys-exit-status/
BTW, I did some testing. On Ruby 1.8.7 on Ubuntu 10.04, I don't get a error. With Ruby 1.9.3, I do. With JRuby 1.6.4 on Ubuntu in both 1.8 and 1.9 modes, I don't get an error. On OS X, with 1.8.7, 1.9.2 and 1.9.3, I don't get an error. The behavior is obviously dependent on your Ruby version and platform.