├── Applications └── FileMonitor │ └── start.php └── README.md /Applications/FileMonitor/start.php: -------------------------------------------------------------------------------- 1 | name = 'FileMonitor'; 16 | // 改进程收到reload信号时,不执行reload 17 | $worker->reloadable = false; 18 | // 所有被监控的文件,key为inotify id 19 | $monitor_files = array(); 20 | 21 | // 进程启动后创建inotify监控句柄 22 | $worker->onWorkerStart = function($worker) 23 | { 24 | if(!extension_loaded('inotify')) 25 | { 26 | echo "FileMonitor : Please install inotify extension.\n"; 27 | return; 28 | } 29 | 30 | global $monitor_dir, $monitor_files; 31 | // 初始化inotify句柄 32 | $worker->inotifyFd = inotify_init(); 33 | // 设置为非阻塞 34 | stream_set_blocking($worker->inotifyFd, 0); 35 | // 递归遍历目录里面的文件 36 | $dir_iterator = new RecursiveDirectoryIterator($monitor_dir); 37 | $iterator = new RecursiveIteratorIterator($dir_iterator); 38 | foreach ($iterator as $file) 39 | { 40 | // 只监控php文件 41 | if(pathinfo($file, PATHINFO_EXTENSION) != 'php') 42 | { 43 | continue; 44 | } 45 | // 把文件加入inotify监控,这里只监控了IN_MODIFY文件更新事件 46 | $wd = inotify_add_watch($worker->inotifyFd, $file, IN_MODIFY); 47 | $monitor_files[$wd] = $file; 48 | } 49 | // 监控inotify句柄可读事件 50 | Worker::$globalEvent->add($worker->inotifyFd, EventInterface::EV_READ, 'check_files_change'); 51 | }; 52 | 53 | // 检查哪些文件被更新,并执行reload 54 | function check_files_change($inotify_fd) 55 | { 56 | global $monitor_files; 57 | // 读取有哪些文件事件 58 | $events = inotify_read($inotify_fd); 59 | if($events) 60 | { 61 | // 检查哪些文件被更新了 62 | foreach($events as $ev) 63 | { 64 | // 更新的文件 65 | $file = $monitor_files[$ev['wd']]; 66 | echo $file ." update and reload\n"; 67 | unset($monitor_files[$ev['wd']]); 68 | // 需要把文件重新加入监控 69 | $wd = inotify_add_watch($inotify_fd, $file, IN_MODIFY); 70 | $monitor_files[$wd] = $file; 71 | } 72 | // 给父进程也就是主进程发送reload信号 73 | posix_kill(posix_getppid(), SIGUSR1); 74 | } 75 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # workerman-filemonitor-inotify 2 | 监控文件更新并自动reload workerman(此版本需要安装inotify扩展)。 3 | 4 | 默认只监控Applications目录,如果要监控其它目录,请更改Applications/FileMonitor/start.php中$monitor_dir,路径最好使用绝对路径。 5 | 6 | 7 | # 注意 8 | 只能更新onXXX中加载的文件,启动脚本直接加载的文件和代码无法自动更新。 9 | 10 | 只有在debug模式启动后才有效,daemon模式不生效。 11 | 12 | # 使用 13 | 直接将Applications下的FileMonitor目录拷贝到你自己的Applications目录下,重启workerman即可 14 | --------------------------------------------------------------------------------