summaryrefslogtreecommitdiff
path: root/ruby_1_8_5/lib/open3.rb
diff options
context:
space:
mode:
Diffstat (limited to 'ruby_1_8_5/lib/open3.rb')
-rw-r--r--ruby_1_8_5/lib/open3.rb82
1 files changed, 82 insertions, 0 deletions
diff --git a/ruby_1_8_5/lib/open3.rb b/ruby_1_8_5/lib/open3.rb
new file mode 100644
index 0000000000..f722252b1c
--- /dev/null
+++ b/ruby_1_8_5/lib/open3.rb
@@ -0,0 +1,82 @@
+# 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| ... }
+
+module Open3
+ #[stdin, stdout, stderr] = popen3(command);
+ 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
+ pi.each{|p| p.close unless p.closed?}
+ end
+ end
+ pi
+ end
+ module_function :popen3
+end
+
+if $0 == __FILE__
+ a = Open3.popen3("nroff -man")
+ Thread.start do
+ while line = gets
+ a[0].print line
+ end
+ a[0].close
+ end
+ while line = a[1].gets
+ print ":", line
+ end
+end