首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ruby -与永续子进程交互

ruby -与永续子进程交互
EN

Stack Overflow用户
提问于 2013-10-26 03:00:33
回答 1查看 281关注 0票数 0

我想知道我如何与无休止的(永恒的循环)儿童过程互动。

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

代码语言:javascript
复制
loop do
    str = gets
    puts str.upcase
end

main.rb:

代码语言:javascript
复制
Process.spawn("ruby loop_puts.rb",{:out=>$stdout, :in=>$stdin})

我想把一些字母,而不是我的手键入,并获得结果(不是先前的结果)的变量。

我该怎么做?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-26 08:39:28

有很多方法可以做到这一点,很难在没有更多上下文的情况下推荐一种方法。

这里有一种使用分叉过程和管道的方法:

代码语言:javascript
复制
# 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消息队列

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19602327

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档