等待popen3进程完成?

时间:2012-07-29 15:44:17

标签: ruby-on-rails ruby process popen

我有一个使用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

我做错了什么?

2 个答案:

答案 0 :(得分:1)

只是一个猜测:也许您还必须使用标准输出,所以可能会添加像

这样的行
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

解决了这个问题?

答案 1 :(得分:1)

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

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