我想知道我如何与无休止的(永恒的循环)儿童过程互动。
loop_puts.rb的源代码,子进程:
loop do
str = gets
puts str.upcase
endmain.rb:
Process.spawn("ruby loop_puts.rb",{:out=>$stdout, :in=>$stdin})我想把一些字母,而不是我的手键入,并获得结果(不是先前的结果)的变量。
我该怎么做?
谢谢
发布于 2013-10-26 08:39:28
有很多方法可以做到这一点,很难在没有更多上下文的情况下推荐一种方法。
这里有一种使用分叉过程和管道的方法:
# 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在这里的文档。请注意,这可能并不是所有的平台都起作用。
https://stackoverflow.com/questions/19602327
复制相似问题