2

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

这是我使用的函数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

我究竟做错了什么?

4

2 回答 2

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

解决问题?

于 2013-03-20T09:48:13.117 回答
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
于 2013-03-21T15:45:24.930 回答