Skip to content

Commit

Permalink
Change stream input writting to wait until pipe is writable
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrmurach committed Jul 16, 2017
1 parent b63d169 commit 1840028
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion lib/tty/command/process_runner.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ class Command
class ProcessRunner
include Execute

# the command to be spawned
attr_reader :cmd

# Initialize a Runner object
#
# @param [Printer] printer
Expand All @@ -30,7 +32,7 @@ def run!
start = Time.now

spawn(cmd) do |pid, stdin, stdout, stderr|
stdin.write cmd.options[:data]
write_stream(stdin)
stdout_data, stderr_data = read_streams(stdout, stderr)

runtime = Time.now - start
Expand Down Expand Up @@ -66,6 +68,31 @@ def handle_timeout(runtime, pid)
end
end

# @api private
def write_stream(stdin)
data = cmd.options[:data]
return unless data
writers = [stdin]

# wait when ready for writing to pipe
_, writable = IO.select(nil, writers, writers, cmd.options[:timeout])
return if writable.nil?

while writers.any?
writable.each do |fd|
begin
err = nil
size = fd.write(data)
data = data.byteslice(size..-1)
rescue Errno::EPIPE => err
end
if err || data.bytesize == 0
writers.delete(stdin)
end
end
end
end

# @api private
def read_streams(stdout, stderr)
stdout_data = ''
Expand Down

0 comments on commit 1840028

Please sign in to comment.