Skip to content

Instantly share code, notes, and snippets.

@vasi
Created December 16, 2014 18:40
Show Gist options
  • Select an option

  • Save vasi/8ffc21bc09ac8fe38f76 to your computer and use it in GitHub Desktop.

Select an option

Save vasi/8ffc21bc09ac8fe38f76 to your computer and use it in GitHub Desktop.
Open3::capture3 for Ruby 1.8.x
#!/usr/bin/ruby
def capture3(*cmd)
# Force no shell expansion, by using a non-plain string. See ruby docs:
#
# `If the first argument is a two-element array, the first element is the
# command to be executed, and the second argument is used as the argv[0]
# value, which may show up in process listings.'
cmd[0] = [cmd[0], cmd[0]]
rout, wout = IO.pipe
rerr, werr = IO.pipe
pid = fork do
rerr.close
rout.close
STDERR.reopen(werr)
STDOUT.reopen(wout)
exec(*cmd)
end
wout.close
werr.close
out = rout.read
err = rerr.read
Process.wait(pid)
rout.close
rerr.close
return [$?, out, err]
end
def test(*cmd)
st, err, out = capture3(*cmd)
p st
p err
p out
puts
end
test('ls', '/var')
test('ls', '/foo')
test('lfhlkhladfla')
test('ls && ls')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment