Skip to content

Instantly share code, notes, and snippets.

@svenyurgensson
Forked from mislav/cmd.rb
Created September 5, 2012 05:17
Show Gist options
  • Save svenyurgensson/3630944 to your computer and use it in GitHub Desktop.
Save svenyurgensson/3630944 to your computer and use it in GitHub Desktop.
Execute a command, return its output, error stream and exit status
# 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