php如何正确使用inotify实例进行目录监控
好的,我需要一个目录监视器来不断扫描目录以查找添加的新 .txt 文件。打开 .txt 文件,读取/解析内容并将数据写入 mysql 表。我正在研究 inotify ,它看起来很强大并且可以完成这项任务,但我不太明白命令序列如何完成我上面提到的任务。
这是一个潜在的例子(告诉我我是否正确地考虑了这个问题):
$fd = inotify_init();
$watch_descriptor = inotify_add_watch($fd, '/some/system/dir/', IN_CREATE);
// Loop forever (never break out of loop since I want to ALWAYS monitor this dir)
while (true) {
$events = inotify_read($fd);
//THIS IS WHERE I DON'T KNOW HOW TO OPEN THE NEWLY CREATED FILE
//PLEASE HELP HERE WITH HOW TO SUCCESSFULLY CREATE THE EVENT ACTIONS
/*
1) OPEN FILE
2) READ/PARSE CONTENTS
3) CREATE MYSQL INSERT STATEMENT
4) DELETE FILE
*/
}
这带来的一个问题是:继续这个循环会永远消耗大量的处理器容量吗?以及:如果是这样,这真的是我应该用来实现我的目标的方法吗?
任何帮助理解 inotify 和实现我的目标所需的顺序都会非常有帮助。
先感谢您。
Ok, I'm in need of a dir monitor that continually scans a dir for new .txt files added. Opens the .txt file, reads/parses the content and writes data to a mysql table. I'm looking into inotify which seems like it is robust and can accomplish this task, but I don't quiet understand how the command sequence would look to accomplish what I mentioned above.
Here is a potential example (tell me if I'm thinking through this properly):
$fd = inotify_init();
$watch_descriptor = inotify_add_watch($fd, '/some/system/dir/', IN_CREATE);
// Loop forever (never break out of loop since I want to ALWAYS monitor this dir)
while (true) {
$events = inotify_read($fd);
//THIS IS WHERE I DON'T KNOW HOW TO OPEN THE NEWLY CREATED FILE
//PLEASE HELP HERE WITH HOW TO SUCCESSFULLY CREATE THE EVENT ACTIONS
/*
1) OPEN FILE
2) READ/PARSE CONTENTS
3) CREATE MYSQL INSERT STATEMENT
4) DELETE FILE
*/
}
One question this brings up is: Will continuing this loop forever consume a ridiculous amount of processor capacity? and: If so, is this truly the method I should use to accomplish my goal?
Any help understanding inotify and the sequence required to accomplish my goal would be very helpful.
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,这就是我到目前为止所得到的(想法?):
我还注意到,当没有触发事件来释放系统内存和处理器容量时,inotify 将参与进程阻塞(这解决了我的问题)关注无限 while 循环)。
Alright, so this is what I've got so far (thoughts?):
It has also been brought to my attention that inotify will engage in process blocking when an event is not being triggered to free system memory and processor capacity (which addresses my concern about the infinite while loop).
使用
inotify_read($fd)
从生成的事件中获取信息。php.net 上有一个合理的示例: http://www.php .net/manual/en/function.inotify-init.php
至于 while 循环,inotify_read() 将阻塞直到有事件发生,因此它不会持续旋转。
Use
inotify_read($fd)
to get information from the generated event.There's a reasonable example over at php.net: http://www.php.net/manual/en/function.inotify-init.php
As for the while loop, inotify_read() will block until there is an event, so it's not as if it's going to be doing a constant spin.