使用php和inotify跟踪文件夹

时间:2016-05-04 19:51:21

标签: php php-5.5 inotify

我需要帮助才能理解如何使用PHP进行inotify工作。 我有一个主文件,我调用我创建的inotify类的实例。

这工作30秒然后php抛出超时错误。在那个时间窗口中,它实际上可以打印来自新文件和已删除文件的信息。它有点工作,但......

我对你们的问题是:

  1. 我怎样才能使它持久稳定。我的意思是我可以设置无限时间的超时请求,但这似乎不是一个好习惯。怎么处理这个?
  2. 它应该像这样工作?我调用函数和php 在这个循环中挂起,直到发生新的变化?
  3. 我的index.php

    $teste = new Inotify_service();

    $teste->add_watch('files');
    
    class Inotify_service
    {
        private $instance;  
        private $watch_id;
    
        public function __construct()
        {
            $this->instance = inotify_init();
            stream_set_blocking($this->instance, 0); # this is needed so inotify_read while operate in non blocking mode
        }
    
        /**
         * [add_watch Adds a new watch or modify an existing watch for the file or directory specified in pathname]
         * @param [string] $pathname [description]
         */
        public function add_watch($pathname)
        {
            $this->watch_id = inotify_add_watch($this->instance, $pathname, IN_CREATE | IN_DELETE);
    
            while(true){
    
                // read events 
                $events = inotify_read($this->instance);
    
                // if the event is happening within our 'Files directory'
                if ($events[0]['wd'] === $this->watch_id){
                    // a file was created
                    if($events[0]['mask'] === IN_CREATE){
                    printf("Created file: %s in Files directory\n", $events[0]['name']);
                    // a file was deleted
                    } else if ($events[0]['mask'] === IN_DELETE){
                        printf("Deleted file: %s in Files directory\n", $events[0]['name']);
                    }                   
                }
            }
    
            // stop watching our directories
            inotify_rm_watch($this->instance, $this->watch_id);
            // close our inotify instance
            fclose($this->instance);
        }
    

0 个答案:

没有答案