等待popen3过程完成?

问题描述:

我有一个Rails应用程序,使用Open3.popen3。它工作正常,但有时应用程序将继续而不等待该过程完成。等待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 

我在做什么错?

+0

当它的工作原理,在不工作? – Linuxios 2013-03-20 00:52:22

只是一个猜测:也许你也必须消耗标准输出,所以也许像添加

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 

修复该问题的行?

+0

红宝石1.8没有第四个参数,所以我不得不忽略对wait_thr的所有引用;此外,我不得不关闭stdin,运行得到stdout,并且它似乎工作。谢谢! – DGM 2013-03-20 15:26:45

+1

不客气!不幸的是我无法测试代码,所以对于上面的代码中的所有错误感到抱歉。我只记得遇到与open4 gem类似的问题...也许你可以发布正确的代码片段? – severin 2013-03-21 10:18:38

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

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