如何使用 Vala 监控 ~/.local 目录?

How can I monitor the ~/.local directory using 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

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

new MainLoop ().run ();

因为文件监视器存储在一个局部变量中,所以它就像其他变量一样在函数调用结束时被销毁(或者用 GObject 术语 finalised/destructed)

为确保它的寿命足够长,您应该将其设为 class 上的一个字段,然后 FileMonitor 实例 'owned' 由 class 的实例而不是每次调用具体方法

可运行演示 (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 ();
}