如何使用Vala监视〜/ .local目录?

时间:2018-07-04 15:46:17

标签: directory local monitor glib vala

我正在尝试根据Vala documentation监视〜/ .local目录,我可以正确地监视主目录。但我无法监视〜/ .local。

initFileMonitor V1:

public void initFileMonitor(){
    try {
        string homePath = Environment.get_home_dir();
        string filePath = homePath + "/.local";
        File file = File.new_for_path(filePath);
        FileMonitor monitor = file.monitor_directory(FileMonitorFlags.NONE, null);

        print ("\nMonitoring: %s\n", file.get_path ());

        monitor.changed.connect ((src, dest, event) => {
            if (dest != null) {
                 print ("%s: %s, %s\n", event.to_string (), src.get_path (), dest.get_path ());
            } else {
                print ("%s: %s\n", event.to_string (), src.get_path ());
            }
        });
    } catch (Error err) {
        print ("Error: %s\n", err.message);
    }
}

终端输出(无错误,无监视):

Monitoring: /home/srdr/.local

2 个答案:

答案 0 :(得分:2)

由于文件监视器存储在本地变量中,因此就像在函数调用结束时销毁其他变量(或用GObject术语确定/销毁)一样

为确保其寿命足够长,您应该将其设置为类的一个字段,然后FileMonitor实例由该类的实例“拥有”,而不是每次调用特定方法

可运行的演示(valac demo.vala --pkg gio-2.0

class FileMonitorDemo {
    private FileMonitor monitor;

    public void initFileMonitor() {
        var path = Path.build_filename(Environment.get_home_dir(), ".local");
        var file = File.new_for_path(path);
        try {
            monitor = file.monitor_directory(NONE);

            message ("Monitoring: %s", file.get_path ());

            monitor.changed.connect ((src, dest, event) => {
                if (dest != null) {
                    print ("%s: %s, %s\n", event.to_string (), src.get_path (), dest.get_path ());
                } else {
                    print ("%s: %s\n", event.to_string (), src.get_path ());
                }
            });
        } catch (Error err) {
            critical ("Error: %s\n", err.message);
        }
    }
}

void main () {
    var filemon = new FileMonitorDemo();
    filemon.initFileMonitor();
    new MainLoop ().run ();
}

答案 1 :(得分:0)

您需要通过创建主循环并让其等待事件来实际运行监视器:

new MainLoop ().run ();