Created
December 16, 2014 18:40
-
-
Save vasi/8ffc21bc09ac8fe38f76 to your computer and use it in GitHub Desktop.
Open3::capture3 for Ruby 1.8.x
This file contains hidden or 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
| #!/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