lib/open3.rb


DEFINITIONS

This source file includes following functions.


   1  # Usage:
   2  #       require "open3"
   3  #
   4  #       in, out, err = Open3.popen3('nroff -man')
   5  #  or
   6  #       include Open3
   7  #       in, out, err = popen3('nroff -man')
   8  #
   9  
  10  module Open3
  11    #[stdin, stdout, stderr] = popen3(command);
  12    def popen3(*cmd)
  13      pw = IO::pipe   # pipe[0] for read, pipe[1] for write
  14      pr = IO::pipe
  15      pe = IO::pipe
  16  
  17      pid = fork{
  18        # child
  19        fork{
  20          # grandchild
  21          pw[1].close
  22          STDIN.reopen(pw[0])
  23          pw[0].close
  24  
  25          pr[0].close
  26          STDOUT.reopen(pr[1])
  27          pr[1].close
  28  
  29          pe[0].close
  30          STDERR.reopen(pe[1])
  31          pe[1].close
  32  
  33          exec(*cmd)
  34        }
  35        exit!
  36      }
  37  
  38      pw[0].close
  39      pr[1].close
  40      pe[1].close
  41      Process.waitpid(pid)
  42      pi = [pw[1], pr[0], pe[0]]
  43      pw[1].sync = true
  44      if defined? yield
  45        begin
  46          return yield(*pi)
  47        ensure
  48          pi.each{|p| p.close unless p.closed?}
  49        end
  50      end
  51      pi
  52    end
  53    module_function :popen3
  54  end
  55  
  56  if $0 == __FILE__
  57    a = Open3.popen3("nroff -man")
  58    Thread.start do
  59      while line = gets
  60        a[0].print line
  61      end
  62      a[0].close
  63    end
  64    while line = a[1].gets
  65      print ":", line
  66    end
  67  end