0

我想知道如何与永无止境(永恒循环)的子进程进行交互。

loop_puts.rb 的源代码,子进程:

loop do
    str = gets
    puts str.upcase
end

主.rb:

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

我想输入一些字母,而不是手动输入,并在变量中获取结果(不是先前的结果)。

我怎样才能做到这一点?

谢谢

4

1 回答 1

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的一些文档在这里。请注意,这可能不适用于所有平台。

其他可能的方法包括命名管道drb消息队列

于 2013-10-26T08:39:28.817 回答