Skip to content

Instantly share code, notes, and snippets.

@davertron
Last active December 19, 2015 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davertron/6028955 to your computer and use it in GitHub Desktop.
Save davertron/6028955 to your computer and use it in GitHub Desktop.
Ruby Pipes
# I want to capture the output of both forked processes, print it, and then
# end. Currently the program hangs after printing the output from both forked
# processes. I think this is because "reader.eof?" doesn't return true because
# neither sub-process ever calls "writer.close". They don't call that because
# they can't, since exec changes the current process, so any ruby after the
# exec call won't get run.
#
# How do I handle this? Should I not use fork/exec?
# UPDATE: Answer below
reader, writer = IO.pipe
pid1 = fork do
reader.close
$stdout.reopen writer
exec 'echo "Hello from pid1"'
end
Process.detach pid1
pid2 = fork do
reader.close
$stdout.reopen writer
exec 'echo "Hello from pid2"'
end
Process.detach pid2
# This was the problem!!! Close the damn pipe n00b
writer.close
until reader.eof?
puts reader.gets
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment