如何超时一个 vala Subprocess?

问题描述 投票:0回答:1

我试图在GLib.Subprocess中运行一个可执行文件并提取其结果。然而,它可能是一个无限循环,永远不会结束。所以,我希望Subprocess在1秒后结束。这是我尝试过的方法。

string executable = "/path/to/executable";
string input = "some_input";
uint timeout_id = 0;
...
...
try {
    string output_string;
    var subp = new GLib.Subprocess.newv ({executable}, SubprocessFlags.STDIN_PIPE | SubprocessFlags.STDOUT_PIPE);
    timeout_id = GLib.Timeout.add (1, () => {
        subp.force_exit ();
        source_remove ();
        return false;
    });
    subp.communicate_utf8 (input, null, out output_string, null);
} catch (GLib.Error e) {
    print ("Error: %s\n", e.message);
}
...
...
void source_remove () {
    if (timeout_id > 0) {
        Source.remove (timeout_id);
        timeout_id = 0;
    }
}

我也试过使用 {"timeout", "1", executable} 但如果一个可执行文件是一个infinte循环,它就不会停止。

timeout gtk glib vala
1个回答
1
投票

问题出在这一行。

    subp.communicate_utf8 (input, null, out output_string, null);

你使用的是同步的 GSubProcess.communicate_utf8() 调用,它将阻塞直到进程被终止。由于你的超时回调也是在mainloop中调用的(这意味着同一个线程),所以它也不会被调用。为了防止这种情况,你应该使用异步变体。GSubProcess.communicate_utf8_async() .

注意:你不需要 source_remove() 在您的超时回调中调用:GSource将通过返回false自动删除。

© www.soinside.com 2019 - 2024. All rights reserved.