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
上面的我已经测试,确实是正确的。
php
首先,咱们须要达成如下一些共识:html
下载inotify (http://pecl.php.net/package/inotify),解压并安装:linux
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查看。web
接着在/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就不存在有没有操做都须要循环执行。cookie
尝试在/dev/shm/inotify创建一个test.txt的新文件,会在inotify_read返回一个包含全部文件的数组,如:ide
01
02
03
04
05
06
07
08
09
10
|
Array
(
[0] => Array
(
[wd] => 1
[mask] => 256
[cookie] => 0
[name] => test.txt
)
)
|