Shell 在vala/glib中读/写文件管道

Shell 在vala/glib中读/写文件管道,shell,process,glib,vala,spawn,Shell,Process,Glib,Vala,Spawn,我正在使用glib vala函数glib.process.spawn_async_with_pipes()(),它输出一些与stdin、stdout和stderr相对应的int。我如何在Vala中使用这些管道?修改了示例,该示例还将内容写入stdin: private static bool process_line (IOChannel channel, IOCondition condition, string stream_name) { if (condition == IOCo

我正在使用glib vala函数glib.process.spawn_async_with_pipes()(),它输出一些与stdin、stdout和stderr相对应的int。我如何在Vala中使用这些管道?

修改了示例,该示例还将内容写入stdin:

private static bool process_line (IOChannel channel, IOCondition condition, string stream_name) {
    if (condition == IOCondition.HUP) {
        stdout.printf ("%s: The fd has been closed.\n", stream_name);
        return false;
    }

    try {
        string line;
        channel.read_line (out line, null, null);
        stdout.printf ("%s: %s", stream_name, line);
    } catch (IOChannelError e) {
        stdout.printf ("%s: IOChannelError: %s\n", stream_name, e.message);
        return false;
    } catch (ConvertError e) {
        stdout.printf ("%s: ConvertError: %s\n", stream_name, e.message);
        return false;
    }

    return true;
}

public static int main (string[] args) {
    MainLoop loop = new MainLoop ();
    try {
        string[] spawn_args = {"ls", "-l", "-h"};
        string[] spawn_env = Environ.get ();
        Pid child_pid;

        int standard_input;
        int standard_output;
        int standard_error;

        Process.spawn_async_with_pipes ("/",
        spawn_args,
        spawn_env,
        SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
        null,
        out child_pid,
        out standard_input,
        out standard_output,
        out standard_error);

        // stdout:
        IOChannel output = new IOChannel.unix_new (standard_output);
        output.add_watch (IOCondition.IN | IOCondition.HUP, (channel, condition) => {
            return process_line (channel, condition, "stdout");
        });

        // stderr:
        IOChannel error = new IOChannel.unix_new (standard_error);
        error.add_watch (IOCondition.IN | IOCondition.HUP, (channel, condition) => {
            return process_line (channel, condition, "stderr");
        });

        // stdin
        GLib.FileStream input = GLib.FileStream.fdopen (standard_input, "w");
        input.write ("Hello, spawned process!".data);

        ChildWatch.add (child_pid, (pid, status) => {
            // Triggered when the child indicated by child_pid exits
            Process.close_pid (pid);
            loop.quit ();
        });

        loop.run ();
    } catch (SpawnError e) {
        stdout.printf ("Error: %s\n", e.message);
    }
    return 0;
}

除了GLib.FileStream.fdopen,您还可以只使用Posix.write和friends、GLib.UnixOutputStream等。

您链接到的页面有一个完整的示例,演示如何为文件描述符(如标准输出)创建GIOChannel以及如何观看它。。。还是我误解了这个问题?@jku这个页面描述了如何使用std out和std err,而不是std in