Last active
August 29, 2015 14:13
-
-
Save kechako/170b2b154e88708505cc to your computer and use it in GitHub Desktop.
Ruby でコマンドをパイプで接続して実行し、各子プロセスの 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
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