blatant rip-off of Open3::popen3 - does anyone think something like this might
be useful (to have a handle on the spawned processes’ pid?)
-a
open4.rb: Spawn a program like popen, but with stderr, and pid, 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 “open4”
stdin, stdout, stderr, pid = Open4.popen4(‘nroff -man’)
or
include Open4
stdin, stdout, stderr, pid = popen4(‘nroff -man’)
module Open4
#[stdin, stdout, stderr, pid] = popen4(command);
def popen4(*cmd)
pw = IO::pipe # pipe[0] for read, pipe[1] for write
pr = IO::pipe
pe = IO::pipe
pc = IO::pipe
pid = fork{
# child
gcid =
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
pc[1].close
exec(*cmd)
}
pc[0].close
pc[1].puts gcid
pc[1].close
exit!
}
pc[1].close
gcid = pc[0].read.to_i
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
[pw[1], pr[0], pe[0], gcid]
end
module_function :popen4
end
if $0 == FILE
a = Open4.popen4(“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
–
EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
PHONE :: 303.497.6469
ADDRESS :: E/GC2 325 Broadway, Boulder, CO 80305-3328
URL :: Solar-Terrestrial Physics Data | NCEI
TRY :: for l in ruby perl;do $l -e “print "\x3a\x2d\x29\x0a"”;done
===============================================================================