2013-10-26 84 views
0

我不知道如何與永無止境(永恆循環)子進程交互。 loop_puts.rb的紅寶石 - 與永無止境的子進程交互

源代碼,子進程:

loop do 
    str = gets 
    puts str.upcase 
end 

main.rb的:

Process.spawn("ruby loop_puts.rb",{:out=>$stdout, :in=>$stdin}) 

我希望把一些字母,而不是由我的手打字,並得到結果(未先前的結果)在變量中。

我該怎麼做?

感謝

+0

循環過程需要從某處讀取該字母。也許是一個插座,或其他東西。 – akonsu

+0

我不知道從$ stdin讀取是不是一個好主意。得到錯誤? – Taeyun

回答

0

有許多方法可以做到這一點,就很難推薦一個沒有更多的上下文。

下面是一個使用派生進程和管道的一種方法:

# When given '-' as the first param, IO#popen forks a new ruby interpreter. 
# Both parent and child processes continue after the return to the #popen 
# call which returns an IO object to the parent process and nil to the child. 
pipe = IO.popen('-', 'w+') 
if pipe 
    # in the parent process 
    %w(please upcase these words).each do |s| 
    STDERR.puts "sending: #{s}" 
    pipe.puts s # pipe communicates with the child process 
    STDERR.puts "received: #{pipe.gets}" 
    end 
    pipe.puts '!quit' # a custom signal to end the child process 
else 
    # in the child process 
    until (str = gets.chomp) == '!quit' 
    # std in/out here are connected to the parent's pipe 
    puts str.upcase 
    end 
end 

一些文檔IO#popen here。請注意,這可能不適用於所有平臺。

其他可行的方法包括Named Pipesdrbmessage queues