Last active
December 19, 2015 22:39
-
-
Save davertron/6028955 to your computer and use it in GitHub Desktop.
Ruby Pipes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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