Created
August 5, 2011 12:10
-
-
Save mislav/1127400 to your computer and use it in GitHub Desktop.
Execute a command, return its output, error stream and exit status
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
# returns [output string, err string, exit code] | |
def cmd(args, input = nil) | |
parent_read, child_write = IO.pipe | |
err_read, err_write = IO.pipe | |
child_read, parent_write = IO.pipe if input | |
pid = fork do | |
if input | |
parent_write.close | |
$stdin.reopen(child_read) | |
end | |
$stdout.reopen(child_write) | |
$stderr.reopen(err_write) | |
exec(*args) | |
end | |
if input | |
parent_write.write input | |
parent_write.close | |
end | |
Process.wait(pid, 0) | |
child_write.close | |
err_write.close | |
[parent_read.read, err_read.read, $?.exitstatus] | |
end | |
# stdout, stderr, no input | |
p cmd('echo foo 1>&2; echo bar') | |
# with input | |
p cmd('cat -', 'hello kitty') | |
# stdout, stderr with input | |
p cmd('ruby -e "puts STDIN.read; warn \'magic\'; exit 37"', 'hello ruby') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment