dorkahemp972157683 2011-10-28 01:57
浏览 60
已采纳

php如何正确使用inotify实例进行dir监控

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.

  • 写回答

2条回答 默认 最新

  • duandun3178 2011-10-28 03:30
    关注

    Alright, so this is what I've got so far (thoughts?):

    $dir = '/some/system/dir/';
    //create mysql database connection here
    
    $fd = inotify_init();
    $watch_descriptor = inotify_add_watch($fd, $dir, IN_CREATE);
    while (true) {
        $events = inotify_read($fd);
        $filepath = $dir . $events['name'];
        $contents = file_get_contents( $filepath );
        //parse contents and insert records into mysql table (thats the easy part)
        unlink( $filepath );
    }
    //close mysql database connection here
    inotify_rm_watch($fd, $watch_descriptor);
    fclose($fd);
    

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法