访问子进程的STDIN而不捕获STDOUT或STDERR

时间:2013-08-27 15:31:05

标签: ruby ruby-1.9 ruby-2.0

在Ruby中,是否可以防止生成的子进程的标准输入被附加到终端,而不必捕获同一进程的STDOUTSTDERR

  • 反引号和x字符串(`...`%x{...})不起作用,因为它们捕获STDIN。

  • Kernel#system不起作用,因为它会将STDIN附加到 终端(截取^C之类的信号并阻止它们发送 到达我的程序,这是我试图避免的。)

  • Open3不起作用,因为它的方法捕获STDOUT或。{ STDOUTSTDERR

那我该怎么用?

1 个答案:

答案 0 :(得分:1)

如果您使用支持它的平台,则可以使用pipeforkexec执行此操作:

# create a pipe
read_io, write_io = IO.pipe

child = fork do
  # in child

  # close the write end of the pipe
  write_io.close

  # change our stdin to be the read end of the pipe
  STDIN.reopen(read_io)

  # exec the desired command which will keep the stdin just set
  exec 'the_child_process_command'
end

# in parent

# close read end of pipe
read_io.close

# write what we want to the pipe, it will be sent to childs stdin
write_io.write "this will go to child processes stdin"
write_io.close

Process.wait child