【问题标题】:How can I monitor the ~/.local directory using Vala?如何使用 Vala 监控 ~/.local 目录?
【发布时间】:2018-07-04 15:46:17
【问题描述】:

我正在尝试根据Vala documentation监控~/.local目录我可以正确监控home。但我无法监控 ~/.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

【问题讨论】:

    标签: directory local monitor glib vala


    【解决方案1】:

    因为文件监视器存储在局部变量中,所以它就像其他变量在函数调用结束时被销毁(或用 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 ();
    }
    

    【讨论】:

      【解决方案2】:

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

      new MainLoop ().run ();
      

      【讨论】:

      • 但这是一个 Budgie 桌面小程序。我认为它不需要MainLoop。它适用于其他目录。
      • 如果这只是应用程序的一部分,监视器将超出范围并被销毁。
      • 是的,我假设 initFileMonitor 是扩展 Applet 的类的方法,因为在 Python 中,文件监视器应该存储在该类的字段中(例如 self.monitor),然后监视器将由 Applet 实例“拥有”并按预期工作。目前,监视器不属于任何东西,因此在函数调用结束时被销毁
      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-25
      • 2013-01-21
      • 2010-09-11
      相关资源
      最近更新 更多