【问题标题】:ruby - interact with never-end child processruby - 与永无止境的子进程交互
【发布时间】:2013-10-26 03:00:33
【问题描述】:

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

loop_puts.rb 源代码,子进程:

loop do
    str = gets
    puts str.upcase
end

main.rb:

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

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

我该怎么做?

谢谢

【问题讨论】:

  • 循环过程需要从某处读取这封信。也许是一个套接字,或者其他东西。
  • 我想知道从 $stdin 读取是否不是一个好主意。获取错误?

标签: ruby stdout stdin interaction child-process


【解决方案1】:

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

这是使用分叉进程和管道的一种方法:

# 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

【讨论】:

    猜你喜欢
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多