Open3#pipeline_rw
# File tmp/rubies/ruby-4.0.0/lib/open3.rb, line 1014
def pipeline_rw(*cmds, &block)
if Hash === cmds.last
opts = cmds.pop.dup
else
opts = {}
end
in_r, in_w = IO.pipe
opts[:in] = in_r
in_w.sync = true
out_r, out_w = IO.pipe
opts[:out] = out_w
pipeline_run(cmds, opts, [in_r, out_w], [in_w, out_r], &block)
end
Basically a wrapper for Process.spawn that:
-
Creates a child process for each of the given
cmdsby callingProcess.spawn. -
Pipes the
stdoutfrom each child to thestdinof the next child, or, for the first child, from the caller’sstdin, or, for the last child, to the caller’sstdout.
The method does not wait for child processes to exit, so the caller must do so.
With no block given, returns a 3-element array containing:
-
The
stdinstream of the first child process. -
The
stdoutstream of the last child process. -
An array of the wait threads for all of the child processes.
Example:
first_stdin, last_stdout, wait_threads = Open3.pipeline_rw('sort', 'cat -n') # => [#<IO:fd 20>, #<IO:fd 21>, [#<Process::Waiter:0x000055e8de29ab40 sleep>, #<Process::Waiter:0x000055e8de29a690 sleep>]] first_stdin.puts("foo\nbar\nbaz") first_stdin.close # Send EOF to sort. puts last_stdout.read wait_threads.each do |wait_thread| wait_thread.join end
Output:
1 bar 2 baz 3 foo
With a block given, calls the block with the stdin stream of the first child, the stdout stream of the last child, and an array of the wait processes:
Open3.pipeline_rw('sort', 'cat -n') do |first_stdin, last_stdout, wait_threads| first_stdin.puts "foo\nbar\nbaz" first_stdin.close # send EOF to sort. puts last_stdout.read wait_threads.each do |wait_thread| wait_thread.join end end
Output:
1 bar 2 baz 3 foo
Like Process.spawn, this method has potential security vulnerabilities if called with untrusted input; see Command Injection.
If the first argument is a hash, it becomes leading argument env in each call to Process.spawn; see Execution Environment.
If the last argument is a hash, it becomes trailing argument options in each call to Process.spawn; see Execution Options.
Each remaining argument in cmds is one of:
-
A
command_line: a string that begins with a shell reserved word or special built-in, or contains one or more metacharacters. -
An
exe_path: the string path to an executable to be called. -
An array containing a
command_lineor anexe_path, along with zero or more string arguments for the command.