2013-08-27 37 views
3

在Ruby中,是否有可能防止生成的子進程的標準輸入連接到終端,而無需捕獲同一進程的STDOUTSTDERR在不捕獲STDOUT或STDERR的情況下訪問子進程的STDIN

  • 反引號和x字符串(`...`%x{...}),因爲它們捕獲STDIN不起作用。

  • Kernel#system,因爲它留下STDIN連接到 終端(截取信號如^C,防止它們 達到我的程序,這是我試圖避免)不起作用。

  • Open3不起作用,因爲它的方法捕獲或者STDOUT或 兩者STDOUTSTDERR

那我該用什麼?

+0

你爲什麼不花時間來顯示你正在嘗試一些例子做。不要讓我們猜測或試圖設想你的代碼。這是浪費時間。請參閱http://sscce.org/ –

+2

@theTinMan我不明白在這種情況下如何適用。我沒有一些代碼被破壞,我正在嘗試修復,我有一個關於Ruby API的特定問題需要回答。 我已經列出了三個不起作用的例子。你想讓我把這些例子放在上下文中並證明它們不起作用嗎? :confused: – Ajedi32

+0

捕獲STDOUT和STDERR與'open3'一樣,你想避免什麼?如果他們*沒有被父母程序捕獲和管理,你希望他們去哪裏? –

回答

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 
+1

嗯。該解決方案非常適合平臺,但它確實可以做到我想要的。太糟糕Windows不支持fork或exec。 :(它似乎沒有任何平臺獨立的解決方案,所以我現在就去做這件事。 – Ajedi32

相關問題