Skip to content

Instantly share code, notes, and snippets.

@bbrowning
Created December 18, 2014 17:28
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 bbrowning/2a71c8b1f243e04d4cb6 to your computer and use it in GitHub Desktop.
Save bbrowning/2a71c8b1f243e04d4cb6 to your computer and use it in GitHub Desktop.
def popen4(*cmd)
# Use IO.popen4 for JRuby < 9.0.0.0
return IO.popen4(*cmd) unless jruby9k?
opts = {}
in_r, in_w = IO.pipe
opts[:in] = in_r
in_w.sync = true
out_r, out_w = IO.pipe
opts[:out] = out_w
err_r, err_w = IO.pipe
opts[:err] = err_w
child_io = [in_r, out_w, err_w]
parent_io = [in_w, out_r, err_r]
pid = spawn(*cmd, opts)
wait_thr = Process.detach(pid)
child_io.each { |io| io.close }
result = [pid, *parent_io]
if defined? yield
begin
return yield(*result)
ensure
parent_io.each { |io| io.close unless io.closed? }
wait_thr.join
end
end
result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment