‘select’ is suppose to watch some file-descriptors and when an event
occurs then an array is returned containing the affected file-descriptors.
Problem: the array I get returned seems contain something different!!!
To me it seems like the array contains non-affected file-descriptors ???
Am I mistaken?.. notify when theres data to read… how should I do?
cat b.rb
require ‘stringio’
require ‘singleton’
class Redir
include Singleton
def initialize
@out = $stdout
@error = $stderr
end
def set_out(elsewhere)
@out = elsewhere
end
def set_error(elsewhere)
@error = elsewhere
end
def write_out(msg)
msg = “” + msg + “”
@out.write(msg)
end
def write_error(msg)
msg = “” + msg + “”
@error.write(msg)
end
end
def system(command)
# todo: stdin
r1, w1 = IO.pipe # stdout
r2, w2 = IO.pipe # stderr
thread = Thread.new do
loop do
puts “waiting”
res = select([r1, r2], nil, nil, 0.1)[0]
p res
if res.include?(r1)
unless r1.eof
Redir.instance.write_out r1.read
else
puts “r1 not”
end
end
if res.include?(r2)
unless r2.eof
Redir.instance.write_error r2.read
else
puts “r2 not”
end
end
end
end
#sleep 0.3 # if we sleep then no output is captured, why ???
pid = fork do
r1.close; r2.close
$defout.reopen(w1); $stdout.reopen(w1); $stderr.reopen(w2)
exec(command)
# todo: should I care closing w1+w2 correctly?
end
w1.close; w2.close
Process.waitpid(pid)
# todo: Wait until the pipes r1+r2 is flushed completly
sleep 0.5
r1.close; r2.close
thread.kill
end
redir = Redir.instance
s = “”
buf = StringIO.new(s, “w”)
redir.set_out(buf)
redir.set_error(buf)
system(“ruby -e ‘puts "hello"; system("ls main.cpp nonexist")’”)
puts “1”
puts s.split(/\n/).collect { |msg| “OK: “+msg }.join(”\n”)
puts “2”
ruby -w b.rb
/home/neoneye/stow/ruby18_r2/lib/ruby/1.8/singleton.rb:145: warning: redefine instance
waiting
[#IO:0x80fcd54]
waiting
[#IO:0x80fcd54, #IO:0x80fcd18]
r1 not
waiting
[#IO:0x80fcd54, #IO:0x80fcd18]
r1 not
r2 not
SNIP SNIP SNIP SNIP SNIP SNIP SNIP SNIP
SNIP repeats itself many times! SNIP
SNIP SNIP SNIP SNIP SNIP SNIP SNIP SNIP
waiting
[#IO:0x80fcd54, #IO:0x80fcd18]
r1 not
r2 not
waiting
[#IO:0x80fcd54, #IO:0x80fcd18]
r1 not
r2 not
waiting
[#IO:0x80fcd54, #IO:0x80fcd18]
r1 not
r2 not
waiting
1
OK: hello
OK: main.cpp
OK: ls: nonexist: No such file or directory
OK:
2
ruby/machine
ruby -v
ruby 1.8.0 (2003-03-03) [i386-freebsd5.0]
uname -a
FreeBSD P350.home 5.0-RELEASE FreeBSD 5.0-RELEASE #0: Thu Jan 16 22:16:53 GMT 2003 root@hollin.btc.adaptec.com:/usr/obj/usr/src/sys/GENERIC i386
···
–
Simon Strandgaard