2013-10-26 18 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