1

我正在尝试使用 vala 使用带有 spawn_command_line_sync() 的 GLib 启动外部应用程序。根据文档(http://valadoc.org/#!api=glib-2.0/GLib.Process.spawn_sync),您可以传递一个字符串来存储外部应用程序的输出。

虽然这在启动打印几行的脚本时效果很好,但我需要调用一个程序来打印二进制文件的内容。(例如“cat /usr/bin/apt-get”)

有什么方法可以接收外部程序的输出,而不是在字符串中,而是在 DataStream 或类似的东西中?

我打算将外部程序的输出写入文件,因此只需调用“cat /usr/bin/apt-get > outputfile”将是一种替代方法(不是很好),但它似乎不起作用.

无论如何,我希望它获得某种输出流。我将不胜感激任何帮助。

我使用的代码:

using GLib;

static void main(string[] args) {
    string execute = "cat /usr/bin/apt-get";
    string output = "out";

    try {
        GLib.Process.spawn_command_line_sync(execute, out output);
    } catch (SpawnError e) {
        stderr.printf("spawn error!");
        stderr.printf(e.message);
    }

    stdout.printf("Output: %s\n", output);
}
4

2 回答 2

2

GLib.Process.spawn_async_with_pipes会让你做到这一点。它生成进程并为每个stdoutstderrstdin. ValaDoc 中有一个关于如何设置IOChannels 来监视输出的代码示例。

于 2013-02-10T18:19:06.787 回答
1

谢谢你,我必须重读 spawn_async_with_pipes() 返回整数而不是字符串。

这样做有什么问题吗?(除了缓冲区大小为 1)

using GLib;

static void main(string[] args) {

    string[] argv = {"cat", "/usr/bin/apt-get"};
    string[] envv = Environ.get();
    int child_pid;
    int child_stdin_fd;
    int child_stdout_fd;
    int child_stderr_fd;

    try {
        Process.spawn_async_with_pipes(
            ".",
            argv,
            envv,
            SpawnFlags.SEARCH_PATH,
            null,
            out child_pid,
            out child_stdin_fd,
            out child_stdout_fd,
            out child_stderr_fd);

    } catch (SpawnError e) {
        stderr.printf("spawn error!");
        stderr.printf(e.message);
        return;
    }

    FileStream filestream1 = FileStream.fdopen(child_stdout_fd, "r");
    FileStream filestream2 = FileStream.open("./stdout", "w");

    uint8 buf[1];
    size_t t;
    while ((t = filestream1.read(buf, 1)) != 0) {
        filestream2.write(buf, 1);
    }
}
于 2013-02-10T22:58:55.163 回答