使用glib重定向外部应用程序的输出

时间:2013-02-10 17:18:47

标签: glib output vala

我正在尝试使用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);
}

2 个答案:

答案 0 :(得分:2)

GLib.Process.spawn_async_with_pipes会让你这样做。它生成进程并为stdoutstderrstdin中的每一个返回文件描述符。 ValaDoc中有一些代码示例,介绍如何设置IOChannel来监视输出。

答案 1 :(得分: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);
    }
}