2010-11-17 85 views
1

我有一組需要從Ruby腳本運行的任務,但是一個特定任務總是在退出之前等待STDIN上的EOF。如何在Ruby中打開STDIN過程?

很明顯,這會導致腳本在等待子進程結束時掛起。

我有子進程的進程ID,但沒有管道或任何類型的句柄。我怎麼能打開一個進程的STDIN的句柄來發送EOF?

回答

8

編輯:鑑於您沒有啓動腳本,我遇到的解決方案是在您使用您的寶石時將$ stdin置於您的控制之下。我建議是這樣的:

old_stdin = $stdin.dup 
# note that old_stdin.fileno is non-0. 
# create a file handle you can use to signal EOF 
new_stdin = File::open('/dev/null', 'r') 
# and make $stdin use it, instead. 
$stdin.reopen(new_stdin) 
new_stdin.close 
# note that $stdin.fileno is still 0, though now it's using /dev/null for input. 
# replace with the call that runs the external program 
system('/bin/cat') 
# "cat" will now exit. restore the old state. 
$stdin.reopen(old_stdin) 
old_stdin.close 

如果你的Ruby腳本創建的任務,它可以使用 IO::popen。例如, cat,當帶參數運行,將等待EOF標準輸入在退出前,但你可以運行以下命令:

f = IO::popen('cat', 'w') 
f.puts('hello') 
# signals EOF to "cat" 
f.close 

+0

這不是我的腳本啓動的過程中,它實際上是一個寶石。我不想編輯寶石,所以我需要直接發送EOF。 – 2010-11-17 04:48:43

+0

謝謝,這工作! – 2010-11-18 00:52:15