首先,我们需要达成以下一些共识:
/dev/shm 为linux下的内存目录,显然在这个目录下建立的东西会放在内存中,默认可以使用50%的内存,在内存不足时,可通过swap进行切换到磁盘。
inotify是linux下的文件系统事件监控,可以满足各种文件监控需要,提供了诸如inotify_init,inotify_read等接口,需要linux2.6或以上的内核(uname -a查看),cygwin下好像不能实现。
php默认是不提供支持inotify的扩展,所以我们需要通过pecl下载编译安装。
下载inotify (http://pecl.php.net/package/inotify),解压并安装:
tar -xvf inotify-0.1.6.tgzcd inotify-0.1.6/usr/local/php/bin/phpize./configure --with-php-config=/usr/local/php/bin/php-configmake && make install
接着在php.ini文件中加载inotify.so,查看有没有加载成功可通过php -i|grep inotify查看。
接着在/dev/shm建立内存目录,因为队列的处理是需要较高的速度,放到磁盘会有一定的I/O时间消耗,我们建立/dev/shm/inotify目录,然后用php写一个死循环的demo去监控目录,另外,通过变更/dev/shm/inotify目录的文件或属性查看结果:
<?php$notify = inotify_init();$rs = inotify_add_watch($notify, '/dev/shm/inotify', IN_CREATE);//IN_CREATE表示只监控新文件的建立,具体参数列表可以在手册inotify处找到。if(!$rs){ die('fail to watch /dev/shm/inotify');} while(1){ $files = inotify_read($notify); print_r($files); echo 'continue to process next event';}
使用inotify模块比不断地循环和scan目录要灵活且省资源,在inotify_read处,没有收到任何事件之前是会一直阻塞的,所以这里的while就不存在有没有操作都需要循环执行。
尝试在/dev/shm/inotify建立一个test.txt的新文件,会在inotify_read返回一个包含所有文件的数组,如:
Array( [0] => Array ( [wd] => 1 [mask] => 256 [cookie] => 0 <strong style="color:transparent">9来源gaodai#ma#com搞@代~码$网</strong>搞gaodaima代码 [name] => test.txt ))