Ruby Spawn 不接受 IO.pipe

Ruby Spawn not accepting a IO.pipe

我四处搜索,但无法理解为什么会出现错误:

"in `spawn': no implicit conversion of IO into String"

下面的简单方法

def execute_with_timeout(cmd)
  pipe_cmd_out = IO.pipe
  pid = Process.spawn(cmd, :out => pipe_cmd_out, :pgroup => true)
  Process.waitpid(pid, 0)
  pipe_cmd_out.close
  $?.exitstatus == 0
end

我哪里出错了?

谢谢。

PS: 我已经删除了超时代码并将代码减少到您所看到的,错误仍然存​​在

重定向映射 child 进程中的文件描述符,例如:out(或STDOUT1)到以下之一:

  1. io:指定为 io.fileno
    的文件描述符 ...
    ...

来自 pipe() 文档:

pipe() -> [read_io, write_o]:
Creates a pair of pipe endpoints (connected to each other) and returns them as a two-element array of IO objects: [ read_io, write_io ].

http://ruby-doc.org/core-2.2.0/IO.html#method-c-pipe

所以,你可以这样做:

def execute_with_timeout(cmd)
  reader, writer = IO.pipe
  puts reader, writer

  pid = Process.spawn(
    cmd, 
    :pgroup => true,
    :out => writer.fileno,  #Redirect child STDOUT into one end of the pipe.
  )

  Process.waitpid(pid, 0)

  puts reader.gets  #Read from the other end of the pipe in the parent.

  writer.close
  reader.close

  $?.exitstatus == 0
end

result = execute_with_timeout('ls')
puts result

--output:--
#<IO:0x000001009a0140>
#<IO:0x000001009a0118>
1.rb
true

where am I making the error here?

spawn() 文档说:

For redirecting to a file, an array is used instead:

 id = spawn(command, :out=>["log", "w"])  

The array specifies a filename, flags and permission.

http://ruby-doc.org/core-2.1.3/Process.html#method-c-spawn

您的 pipe() 调用 returns IO 数组 objects,您将其用作 :out 键的值。但是因为 spawn() 需要一个字符串数组作为值,ruby 尝试将 IO objects 转换为字符串,这会产生错误:

"in `spawn': no implicit conversion of IO into String"

spawn() 文档确实显示了一个示例,其中与重定向键之一对应的值不是字符串数组:

 :err=>[:child, :out]

(这意味着将 :err(在 child 中)重定向到 child :out)。但是你的 pipe() 数组也不是符号数组。