2003-09-16 13:37:34 -04:00
|
|
|
# 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,
|
|
|
|
# with IO#popen does not allow)
|
|
|
|
#
|
1999-08-13 01:45:20 -04:00
|
|
|
# Usage:
|
|
|
|
# require "open3"
|
|
|
|
#
|
2003-09-16 13:37:34 -04:00
|
|
|
# stdin, stdout, stderr = Open3.popen3('nroff -man')
|
1999-08-13 01:45:20 -04:00
|
|
|
# or
|
|
|
|
# include Open3
|
2003-09-16 13:37:34 -04:00
|
|
|
# stdin, stdout, stderr = popen3('nroff -man')
|
1999-08-13 01:45:20 -04:00
|
|
|
|
|
|
|
module Open3
|
|
|
|
#[stdin, stdout, stderr] = popen3(command);
|
2000-10-25 00:48:41 -04:00
|
|
|
def popen3(*cmd)
|
1999-08-13 01:45:20 -04:00
|
|
|
pw = IO::pipe # pipe[0] for read, pipe[1] for write
|
|
|
|
pr = IO::pipe
|
|
|
|
pe = IO::pipe
|
|
|
|
|
2000-10-20 12:37:01 -04:00
|
|
|
pid = fork{
|
|
|
|
# child
|
2000-10-25 00:48:41 -04:00
|
|
|
fork{
|
|
|
|
# grandchild
|
|
|
|
pw[1].close
|
|
|
|
STDIN.reopen(pw[0])
|
|
|
|
pw[0].close
|
1999-08-13 01:45:20 -04:00
|
|
|
|
2000-10-25 00:48:41 -04:00
|
|
|
pr[0].close
|
|
|
|
STDOUT.reopen(pr[1])
|
|
|
|
pr[1].close
|
1999-08-13 01:45:20 -04:00
|
|
|
|
2000-10-25 00:48:41 -04:00
|
|
|
pe[0].close
|
|
|
|
STDERR.reopen(pe[1])
|
|
|
|
pe[1].close
|
1999-08-13 01:45:20 -04:00
|
|
|
|
2000-10-25 00:48:41 -04:00
|
|
|
exec(*cmd)
|
|
|
|
}
|
2001-05-16 05:05:54 -04:00
|
|
|
exit!
|
2000-10-20 12:37:01 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
pw[0].close
|
|
|
|
pr[1].close
|
|
|
|
pe[1].close
|
2000-10-25 00:48:41 -04:00
|
|
|
Process.waitpid(pid)
|
|
|
|
pi = [pw[1], pr[0], pe[0]]
|
2002-01-29 02:16:09 -05:00
|
|
|
pw[1].sync = true
|
2000-10-20 12:37:01 -04:00
|
|
|
if defined? yield
|
2000-10-25 00:48:41 -04:00
|
|
|
begin
|
2000-11-08 00:29:37 -05:00
|
|
|
return yield(*pi)
|
2000-10-25 00:48:41 -04:00
|
|
|
ensure
|
|
|
|
pi.each{|p| p.close unless p.closed?}
|
|
|
|
end
|
1999-08-13 01:45:20 -04:00
|
|
|
end
|
2000-10-20 12:37:01 -04:00
|
|
|
pi
|
1999-08-13 01:45:20 -04:00
|
|
|
end
|
|
|
|
module_function :popen3
|
|
|
|
end
|
|
|
|
|
|
|
|
if $0 == __FILE__
|
|
|
|
a = Open3.popen3("nroff -man")
|
|
|
|
Thread.start do
|
2000-02-24 22:51:23 -05:00
|
|
|
while line = gets
|
|
|
|
a[0].print line
|
1999-08-13 01:45:20 -04:00
|
|
|
end
|
|
|
|
a[0].close
|
|
|
|
end
|
2000-02-24 22:51:23 -05:00
|
|
|
while line = a[1].gets
|
|
|
|
print ":", line
|
1999-08-13 01:45:20 -04:00
|
|
|
end
|
|
|
|
end
|