访问子进程的STDIN而不捕获STDOUT或STDERR
在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