【问题标题】:Wait for popen3 process to finish?等待 popen3 进程完成?
【发布时间】:2012-07-27 11:22:52
【问题描述】:

我有一个使用 Open3.popen3 的 Rails 应用程序。它工作正常,但有时应用程序会继续运行而无需等待进程完成。

这是我使用的函数 Open3.popen3 的样子(本质上它运行 cat 函数):

def cat_func(var)
  ## some stuff happens 
  exit = 0
  Open3.popen3(" #{cat_command}"){|stdin, stdout, stderr, wait_thr|
    pid = wait_thr.pid 
    error = std err.gets
    exit = wait_thr.value
  }
  #HERE IS TRYING TO INTERCEPT ERRORS:
  if error.match(/^cat:/)
    ### Do something
  end
  call_next_function
end

我做错了什么?

【问题讨论】:

  • 什么时候有效,什么时候无效?

标签: ruby-on-rails ruby process popen


【解决方案1】:

只是一个猜测:也许你还必须消耗 stdout,所以可能添加一行像

def cat_func(var)
  exit = 0
  Open3.popen3(" #{cat_command}") do |stdin, stdout, stderr, wait_thr|
    pid   = wait_thr.pid 
    stdout.gets
    error = stderr.gets
    exit  = wait_thr.value
  end

  # more stuff...
end

解决问题了吗?

【讨论】:

  • ruby 1.8 没有第四个参数,所以我不得不省略所有对 wait_thr 的引用;另外,我不得不关闭标准输入,然后在标准输出上运行,它似乎可以工作。谢谢!
  • 不客气!不幸的是,我无法测试代码,因此对上面文章中的所有错误感到抱歉。我只记得在 open4 gem 上遇到过类似的问题...也许您可以发布正确的代码 sn-p?
【解决方案2】:

为了记录,这是我的最终解决方案:

Open3.popen3(command) do |stdin, stdout, stderr|
  stdin.puts instructions
  stdin.close  # make sure the subprocess is done
  stdout.gets  # and read all output - EOF means the process has completed.
  stderr.gets
end

【讨论】:

    猜你喜欢
    • 2010-11-06
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2019-01-30
    相关资源
    最近更新 更多