【问题标题】:Listen to a background process in vala在 vala 中监听一个后台进程
【发布时间】:2021-07-09 16:21:59
【问题描述】:

我有一个我想在后台收听的命令Process.spawn_command_line_async 是我想要的,但我不知道如何收听响应。该命令将在需要更新时输出行,然后我需要解析该行并相应地运行一个函数。该过程在停止之前不会结束,因此需要在运行时进行监听。

【问题讨论】:

    标签: vala


    【解决方案1】:

    你想要的是Process.spawn_commandline_async_with_pipes ()。瓦拉多克has a code example:

    private static bool process_line (IOChannel channel, IOCondition condition, string stream_name) {
        if (condition == IOCondition.HUP) {
            print ("%s: The fd has been closed.\n", stream_name);
            return false;
        }
    
        try {
            string line;
            channel.read_line (out line, null, null);
            print ("%s: %s", stream_name, line);
        } catch (IOChannelError e) {
            print ("%s: IOChannelError: %s\n", stream_name, e.message);
            return false;
        } catch (ConvertError e) {
            print ("%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");
            });
    
            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) {
            print ("Error: %s\n", e.message);
        }
        return 0;
    }
    
    valac --pkg glib-2.0 GLib.Process.spawn_async_with_pipes.vala
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 2017-11-16
    • 2012-07-30
    • 2013-06-17
    相关资源
    最近更新 更多