Skip to content

Instantly share code, notes, and snippets.

@kechako
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kechako/170b2b154e88708505cc to your computer and use it in GitHub Desktop.
Save kechako/170b2b154e88708505cc to your computer and use it in GitHub Desktop.
Ruby でコマンドをパイプで接続して実行し、各子プロセスの Exit status を取得するサンプル
def cmd_pipe(*commands)
raise TypeError unless commands.is_a?(Array)
raise ArgumentError if commands.size < 2
pids = []
pipes = []
pipe_next = nil
until((cmd = commands.shift).nil?)
pipe_in = pipe_next || $stdin
if commands.empty?
pipe_out = $stdout
else
pipe_next, pipe_out = IO.pipe
pipes << pipe_next << pipe_out
end
pids << spawn(cmd, in: pipe_in, out: pipe_out)
end
pipes.each(&:close)
pids.map { |pid| Process.waitpid2(pid)[1] }
end
# $ cmd1 | cmd2
cmd_piep('cmd1', 'cmd2')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment