在 Ruby 中,是否可以防止生成的子进程的标准输入附加到终端,而不必捕获同一进程的STDOUT
或STDERR
?
-
反引号和x字符串(
`...`
,%x{...}
(不起作用,因为它们捕获STDIN。 -
Kernel#system
不起作用,因为它将 STDIN 附加到终端(拦截^C
等信号并防止它们达到我的程序,这是我试图避免的(。 -
Open3
不起作用,因为它的方法捕获STDOUT
或STDOUT
和STDERR
.
那么我应该使用什么呢?
如果你在一个支持它的平台上,你可以用pipe
、fork
和exec
来做到这一点:
# 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