| Module | Open3 |
| In: |
lib/open3.rb
|
open3.rb: Spawn a program like popen, but with stderr, too. You might also want to use this if you want to bypass the shell. (By passing multiple args, which IO#popen does not allow)
Usage:
require "open3"
stdin, stdout, stderr = Open3.popen3('nroff -man')
or:
include Open3
stdin, stdout, stderr = popen3('nroff -man')
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.
Such as:
Open3.popen3('nroff -man') { |stdin, stdout, stderr| ... }
# File lib/open3.rb, line 27
27: def popen3(*cmd)
28: pw = IO::pipe # pipe[0] for read, pipe[1] for write
29: pr = IO::pipe
30: pe = IO::pipe
31:
32: pid = fork{
33: # child
34: fork{
35: # grandchild
36: pw[1].close
37: STDIN.reopen(pw[0])
38: pw[0].close
39:
40: pr[0].close
41: STDOUT.reopen(pr[1])
42: pr[1].close
43:
44: pe[0].close
45: STDERR.reopen(pe[1])
46: pe[1].close
47:
48: exec(*cmd)
49: }
50: exit!(0)
51: }
52:
53: pw[0].close
54: pr[1].close
55: pe[1].close
56: Process.waitpid(pid)
57: pi = [pw[1], pr[0], pe[0]]
58: pw[1].sync = true
59: if defined? yield
60: begin
61: return yield(*pi)
62: ensure
63: pi.each{|p| p.close unless p.closed?}
64: end
65: end
66: pi
67: end