2 # = open3.rb: Popen, but with stderr, too
4 # Author:: Yukihiro Matsumoto
5 # Documentation:: Konrad Meyer
7 # Open3 gives you access to stdin, stdout, and stderr when running other
12 # Open3 grants you access to stdin, stdout, stderr and a thread to wait the
13 # child process when running another program.
20 # stdin, stdout, stderr, wait_thr = popen3('nroff -man')
22 # Open3.popen3 can also take a block which will receive stdin, stdout,
23 # stderr and wait_thr as parameters.
24 # This ensures stdin, stdout and stderr are closed and
25 # the process is terminated once the block exits.
31 # Open3.popen3('nroff -man') { |stdin, stdout, stderr, wait_thr| ... }
36 # Open stdin, stdout, and stderr streams and start external executable.
37 # In addition, a thread for waiting the started process is noticed.
38 # The thread has a thread variable :pid which is the pid of the started
43 # stdin, stdout, stderr, wait_thr = Open3.popen3(cmd)
44 # pid = wait_thr[:pid] # pid of the started process.
46 # stdin.close # stdin, stdout and stderr should be closed in this form.
49 # exit_status = wait_thr.value # Process::Status object returned.
53 # Open3.popen3(cmd) { |stdin, stdout, stderr, wait_thr| ... }
55 # The parameter +cmd+ is passed directly to Kernel#spawn.
57 # wait_thr.value waits the termination of the process.
58 # The block form also waits the process when it returns.
60 # Closing stdin, stdout and stderr does not wait the process.
63 pw = IO::pipe # pipe[0] for read, pipe[1] for write
67 pid = spawn(*cmd, STDIN=>pw[0], STDOUT=>pr[1], STDERR=>pe[1])
68 wait_thr = Process.detach(pid)
72 pi = [pw[1], pr[0], pe[0], wait_thr]
78 [pw[1], pr[0], pe[0]].each{|p| p.close unless p.closed?}
84 module_function :popen3
88 a = Open3.popen3("nroff -man")
95 while line = a[1].gets