Skip to content

Instantly share code, notes, and snippets.

@mislav
Created August 5, 2011 12:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mislav/1127400 to your computer and use it in GitHub Desktop.
Save mislav/1127400 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