Module: Open3

Extended by:
Open3
Included in:
Open3
Defined in:
lib/grit/open3_detach.rb

Instance Method Summary collapse

Instance Method Details

#popen3(*cmd) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/grit/open3_detach.rb', line 4

def popen3(*cmd)
  pw = IO::pipe   # pipe[0] for read, pipe[1] for write
  pr = IO::pipe
  pe = IO::pipe

  pid = fork{
    # child
    fork{
      # grandchild
      pw[1].close
      STDIN.reopen(pw[0])
      pw[0].close

      pr[0].close
      STDOUT.reopen(pr[1])
      pr[1].close

      pe[0].close
      STDERR.reopen(pe[1])
      pe[1].close

      exec(*cmd)
    }
    exit!(0)
  }

  pw[0].close
  pr[1].close
  pe[1].close
  Process.waitpid(pid)
  pi = [pw[1], pr[0], pe[0]]
  pw[1].sync = true
  if defined? yield
    begin
      return yield(*pi)
    ensure
      Process.detach(pid) if pid
      pi.each { |p| p.close unless p.closed? }
    end
  end
  pi
end