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