php使用inotify实现队列处理

php使用inotify实现队列处理
参考如下文章:
http://blog.jiunile.com/php%E4%BD%BF%E7%94%A8inotify%E5%AE%9E%E7%8E%B0%E9%98%9F%E5%88%97%E5%A4%84%E7%90%86.html
http://sexywp.com/use-inotify-to-monitor-file-system.htm
上面的我已经测试,确实是正确的。

首先,我们需要达成以下一些共识:

  • /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),解压并安装:

1
2
3
4
5
tar -xvf inotify-0.1.6.tgz
cd inotify-0.1.6
/usr/local/php5/bin/phpize
./configure --with-php-config=/usr/local/php5/bin/php-config
make && make install

接着在php.ini文件中加载inotify.so,查看有没有加载成功可通过php -i|grep inotify查看。

接着在/dev/shm建立内存目录,因为队列的处理是需要较高的速度,放到磁盘会有一定的I/O时间消耗,我们建立/dev/shm/inotify目录,然后用php写一个死循环的demo去监控目录,另外,通过变更/dev/shm/inotify目录的文件或属性查看结果:

01
02
03
04
05
06
07
08
09
10
11
12
<?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返回一个包含所有文件的数组,如:

01
02
03
04
05
06
07
08
09
10
Array
(
    [0] => Array
        (
            [wd] => 1
            [mask] => 256
            [cookie] => 0
            [name] => test.txt
        )
)
 
 
原文地址:https://www.cnblogs.com/voiphudong/p/3291626.html