Class: EventMachine::POSIX::Spawn::Child::ReadableStream

Inherits:
Stream
  • Object
show all
Defined in:
lib/em/posix/spawn/child.rb

Defined Under Namespace

Classes: Listener

Constant Summary collapse

BUFSIZE =

Maximum buffer size for reading

(64 * 1024)

Instance Attribute Summary

Attributes inherited from Stream

#buffer

Instance Method Summary collapse

Methods inherited from Stream

#closed?, #force_encoding

Constructor Details

#initialize(buffer, name, discard_output = false, &block) ⇒ ReadableStream

Returns a new instance of ReadableStream.



405
406
407
408
409
# File 'lib/em/posix/spawn/child.rb', line 405

def initialize(buffer, name, discard_output = false, &block)
  super(buffer, name, &block)
  @discard_output = discard_output
  @after_read = []
end

Instance Method Details

#after_read(&block) ⇒ Object



423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# File 'lib/em/posix/spawn/child.rb', line 423

def after_read(&block)
  if block
    listener = Listener.new(@name, &block)
    if @closed
      # If this stream is already closed, then close the listener in
      # the next Event Machine tick. This ensures that the listener
      # receives the entire buffer if it attaches to the process only
      # after its completion.
      EM.next_tick do
        listener.close(@buffer)
      end
    elsif !@buffer.empty?
      # If this stream's buffer is non-empty, pass it to the listener
      # in the next tick to avoid having to wait for the next piece
      # of data to be read.
      EM.next_tick do
        listener.call(@buffer)
      end
    end

    @after_read << listener
    listener
  end
end

#closeObject



411
412
413
414
415
416
417
418
419
420
421
# File 'lib/em/posix/spawn/child.rb', line 411

def close
  # Ensure that the listener receives the entire buffer if it
  # attaches to the process only just before the stream is closed.
  @after_read.each do |listener|
    listener.close(@buffer)
  end

  @after_read.clear

  super
end

#notify_readableObject



448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
# File 'lib/em/posix/spawn/child.rb', line 448

def notify_readable
  # Close and detach are decoupled, check if this notification is
  # supposed to go through.
  return if closed?

  begin
    out = @io.read_nonblock(BUFSIZE)
    @buffer << out unless @discard_output
    @after_read.each { |listener| listener.call(@buffer) }
  rescue Errno::EAGAIN, Errno::EINTR
  rescue EOFError
    close
    set_deferred_success
  end
end