Skip to content

Commit

Permalink
quit trying to stream IO streams that have closed
Browse files Browse the repository at this point in the history
  • Loading branch information
timcharper committed Apr 22, 2010
1 parent 6f39b21 commit 276be76
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
11 changes: 6 additions & 5 deletions lib/background_process/io_helpers.rb
Expand Up @@ -4,17 +4,18 @@ def detect(streams = [], timeout = nil, &block)
begin
Timeout::timeout(timeout) do
# Something that should be interrupted if it takes too much time...
while true
available_streams, _, _ = Kernel.select(streams, nil, nil, 1)
available_streams.each do |s|
until streams.empty?
active_streams, _, _ = Kernel.select(streams, nil, nil, 1)
active_streams.each do |s|
(streams -= [s]; next) if s.eof?
content = s.gets
if result = (block.arity == 1 ? yield(content) : yield(s, content))
return result
end
end if available_streams
end if active_streams
end
end
true
nil
rescue Timeout::Error
nil
end
Expand Down
15 changes: 15 additions & 0 deletions spec/background_process/background_process_spec.rb
Expand Up @@ -110,5 +110,20 @@
raise(Spec::Expectations::ExpectationNotMetError, "expected to not yield the block")
end
end

it "quits when the process does" do
process = BackgroundProcess.run("sleep 0.3")
started_waiting = Time.now
result = process.detect(:both, 1) do |line|
line.should_not be_nil
end
result.should be_nil
(Time.now - started_waiting).should < 0.4
end

it "yields the very last bit of the process output" do
process = BackgroundProcess.run("echo hello; printf hi")
process.detect(:both, 1) { |line| line == "hi" }.should == true
end
end
end

0 comments on commit 276be76

Please sign in to comment.