| Module | Open3 |
| In: |
lib/open3.rb
|
Open3 grants you access to stdin, stdout, and stderr when running another program. Example:
require "open3"
include Open3
stdin, stdout, stderr = popen3('nroff -man')
Open3.popen3 can also take a block which will receive stdin, stdout and stderr as parameters. This ensures stdin, stdout and stderr are closed once the block exits. Example:
require "open3"
Open3.popen3('nroff -man') { |stdin, stdout, stderr| ... }
Open stdin, stdout, and stderr streams and start external executable. Non-block form:
require 'open3' [stdin, stdout, stderr] = Open3.popen3(cmd)
Block form:
require 'open3'
Open3.popen3(cmd) { |stdin, stdout, stderr| ... }
The parameter cmd is passed directly to Kernel#exec.
# File lib/open3.rb, line 46
46: def popen3(*cmd)
47: pw = IO::pipe # pipe[0] for read, pipe[1] for write
48: pr = IO::pipe
49: pe = IO::pipe
50:
51: pid = fork{
52: # child
53: fork{
54: # grandchild
55: pw[1].close
56: STDIN.reopen(pw[0])
57: pw[0].close
58:
59: pr[0].close
60: STDOUT.reopen(pr[1])
61: pr[1].close
62:
63: pe[0].close
64: STDERR.reopen(pe[1])
65: pe[1].close
66:
67: exec(*cmd)
68: }
69: exit!(0)
70: }
71:
72: pw[0].close
73: pr[1].close
74: pe[1].close
75: Process.waitpid(pid)
76: pi = [pw[1], pr[0], pe[0]]
77: pw[1].sync = true
78: if defined? yield
79: begin
80: return yield(*pi)
81: ensure
82: pi.each{|p| p.close unless p.closed?}
83: end
84: end
85: pi
86: end