PageRenderTime 49ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/ruby/1.8/open3.rb

https://bitbucket.org/nicksieger/jruby
Ruby | 102 lines | 18 code | 3 blank | 81 comment | 4 complexity | 0b1b76d7ab5c33e4bc561c03d3c44697 MD5 | raw file
Possible License(s): GPL-3.0, JSON
  1. #
  2. # = open3.rb: Popen, but with stderr, too
  3. #
  4. # Author:: Yukihiro Matsumoto
  5. # Documentation:: Konrad Meyer
  6. #
  7. # Open3 gives you access to stdin, stdout, and stderr when running other
  8. # programs.
  9. #
  10. #
  11. # Open3 grants you access to stdin, stdout, and stderr when running another
  12. # program. Example:
  13. #
  14. # require "open3"
  15. # include Open3
  16. #
  17. # stdin, stdout, stderr = popen3('nroff -man')
  18. #
  19. # Open3.popen3 can also take a block which will receive stdin, stdout and
  20. # stderr as parameters. This ensures stdin, stdout and stderr are closed
  21. # once the block exits. Example:
  22. #
  23. # require "open3"
  24. #
  25. # Open3.popen3('nroff -man') { |stdin, stdout, stderr| ... }
  26. #
  27. module Open3
  28. #
  29. # Open stdin, stdout, and stderr streams and start external executable.
  30. # Non-block form:
  31. #
  32. # require 'open3'
  33. #
  34. # stdin, stdout, stderr = Open3.popen3(cmd)
  35. #
  36. # Block form:
  37. #
  38. # require 'open3'
  39. #
  40. # Open3.popen3(cmd) { |stdin, stdout, stderr| ... }
  41. #
  42. # The parameter +cmd+ is passed directly to Kernel#exec.
  43. #
  44. def popen3(*cmd, &p)
  45. IO::popen3(*cmd, &p)
  46. # pw = IO::pipe # pipe[0] for read, pipe[1] for write
  47. # pr = IO::pipe
  48. # pe = IO::pipe
  49. #
  50. # pid = fork{
  51. # # child
  52. # fork{
  53. # # grandchild
  54. # pw[1].close
  55. # STDIN.reopen(pw[0])
  56. # pw[0].close
  57. #
  58. # pr[0].close
  59. # STDOUT.reopen(pr[1])
  60. # pr[1].close
  61. #
  62. # pe[0].close
  63. # STDERR.reopen(pe[1])
  64. # pe[1].close
  65. #
  66. # exec(*cmd)
  67. # }
  68. # exit!(0)
  69. # }
  70. #
  71. # pw[0].close
  72. # pr[1].close
  73. # pe[1].close
  74. # Process.waitpid(pid)
  75. # pi = [pw[1], pr[0], pe[0]]
  76. # pw[1].sync = true
  77. # if defined? yield
  78. # begin
  79. # return yield(*pi)
  80. # ensure
  81. # pi.each{|p| p.close unless p.closed?}
  82. # end
  83. # end
  84. # pi
  85. end
  86. module_function :popen3
  87. end
  88. if $0 == __FILE__
  89. a = Open3.popen3("nroff -man")
  90. Thread.start do
  91. while line = gets
  92. a[0].print line
  93. end
  94. a[0].close
  95. end
  96. while line = a[1].gets
  97. print ":", line
  98. end
  99. end