【问题标题】:Linux: How to execute script when directory is written toLinux:写入目录时如何执行脚本
【发布时间】:2014-03-01 05:28:46
【问题描述】:

我是 Linux 新手,这似乎是一个很容易解决的问题,但我不知所措。我想在写入某个目录时执行脚本。我计划在该文件夹上设置某种监视程序,以触发脚本运行。我在网上找到了有关使用 incron、watch 或 inotify 的条目。我认为 incron 是我想要的,但绝对没有在线资源可以引导您完成整个过程。我想使用 incron 是对的吗?如果是这样,我该如何让它工作?在我的 incrontab 中,我有

/home/myusername/folder IN_CLOSE_WRITE /var/www/runMe.sh

我已经尝试了一些变体,但看起来是正确的。我已经在网上找了几个小时了,所以我很沮丧。我创建了一个 incron.allow 文件,其中列出了 root 和我的用户名,我启动了 incrond 服务,但是当上面指定的目录被写入 shell 脚本时没有执行。我在 CentOS 6.5 上,该目录正在被另一台机器 ssh 写入。感谢您提供的任何帮助。

【问题讨论】:

    标签: linux centos6 incron


    【解决方案1】:

    这是一个 Gtkmm 示例,用于检测何时在目录中创建文件或文件夹:

    #include <glibmm.h>
    #include <giomm.h>
    #include <iostream>
    
    void file_changed(const Glib::RefPtr<Gio::File>& file, const Glib::RefPtr<Gio::File>&   otherFile, Gio::FileMonitorEvent event)
    {
        if(event == Gio::FILE_MONITOR_EVENT_CREATED ){
            std::cout << "File created: " << file->get_path() << std::endl;
        }
    }
    
    int main(int argc, char* argv[]) {
        if(argc < 2) {
            std::cerr << "Usage: " << argv[0] << " directory_to_monitor" << std::endl;
            return 1;
        }
        Glib::init();
        Gio::init();
    
        Glib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create();
    
        Glib::RefPtr<Gio::File> file = Gio::File::create_for_path(argv[1]);
        Glib::RefPtr<Gio::FileMonitor> monitor = file->monitor_directory();
        monitor->signal_changed().connect(sigc::ptr_fun(file_changed));
        loop->run();
        return 0;
    }
    

    编译

    g++ -o test test.cpp $(pkg-config --cflags --libs glibmm-2.4 giomm-2.4)
    

    【讨论】:

      【解决方案2】:

      您应该阅读inotify(7) 并考虑使用incron

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-26
        • 1970-01-01
        • 2011-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-26
        • 2020-08-08
        相关资源
        最近更新 更多