lib/tty/command/child_process.rb in tty-command-0.7.0 vs lib/tty/command/child_process.rb in tty-command-0.8.0

- old
+ new

@@ -23,12 +23,13 @@ # @api public def spawn(cmd) process_opts = normalize_redirect_options(cmd.options) binmode = cmd.options[:binmode] || false pty = cmd.options[:pty] || false + verbose = cmd.options[:verbose] - pty = try_loading_pty if pty + pty = try_loading_pty(verbose) if pty require('pty') if pty # load within this scope # Create pipes in_rd, in_wr = pty ? PTY.open : IO.pipe('utf-8') # reading out_rd, out_wr = pty ? PTY.open : IO.pipe('utf-8') # writing @@ -63,37 +64,44 @@ end opts.merge!(process_opts) pid = Process.spawn(cmd.to_command, opts) - # close in parent process - [in_rd, out_wr, err_wr].each { |fd| fd.close if fd } + # close streams in parent process talking to the child + close_fds(in_rd, out_wr, err_wr) tuple = [pid, in_wr, out_rd, err_rd] if block_given? begin return yield(*tuple) ensure # ensure parent pipes are closed - [in_wr, out_rd, err_rd].each { |fd| fd.close if fd && !fd.closed? } + close_fds(in_wr, out_rd, err_rd) end else tuple end end module_function :spawn + # Close all streams + # @api private + def close_fds(*fds) + fds.each { |fd| fd && !fd.closed? && fd.close } + end + module_function :close_fds + # Try loading pty module # # @return [Boolean] # # @api private - def try_loading_pty + def try_loading_pty(verbose = false) require 'pty' true rescue LoadError - warn("Requested PTY device but the system doesn't support it.") + warn("Requested PTY device but the system doesn't support it.") if verbose false end module_function :try_loading_pty # Normalize spawn fd into :in, :out, :err keys.