微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

收听 vala 中的后台进程

如何解决收听 vala 中的后台进程

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

解决方法

您想要的是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",e.message);
        return false;
    } catch (ConvertError e) {
        print ("%s: ConvertError: %s\n",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,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,"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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?