inotify监控Linux文件系统的必备利器
希望追踪文件与目录的创建或删除事件,因此您可以掩去打开、关闭以及属性改变事件. 如果您对文件或目录的重命名和移动不感兴趣,您也可以掩去各种移动事件.关于更多细节,参见 inotify 帮助信息.
清单 2. inotify-test.c 的简单主程序 1./* Signal handler that simply resets a flag to cause termination */ 2.void signal_handler (int signum) 3.{ 4.keep_running = 0; 5.} 6.int main (int argc, char **argv) 7.{ 8./* This is the file descriptor for the inotify watch */ 9.int inotify_fd; 10.keep_running = 1; 11./* Set a ctrl-c signal handler */ 12.if (signal (SIGINT, signal_handler) == SIG_IGN) 13.{ 14./* Reset to SIG_IGN (ignore) if that was the prior state */ 15.signal (SIGINT, SIG_IGN); 16.} 17./* First we open the inotify dev entry */ 18.inotify_fd = open_inotify_fd (); 19.if (inotify_fd > 0) 20.{ 21./* We will need a place to enqueue inotify events, 22.this is needed because if you do not read events 23.fast enough, you will miss them. This queue is 24.probably too small if you are monitoring something 25.like a directory with a lot of files and the directory 26.is deleted. 27.*/ 28.queue_t q; 29.q = queue_create (128); 30./* This is the watch descriptor returned for each item we are 31.watching. A real application might keep these for some use 32.in the application. This sample only makes sure that none of 33.the watch descriptors is less than 0. 34.*/ 35.int wd; 36./* Watch all events (IN_ALL_EVENTS) for the directories and 37.files passed in as arguments. 38.Read the article for why you might want to alter this for 39.more efficient inotify use in your app. 40.*/ 41.int index; 42.wd = 0; 43.printf("n"); 44.for (index = 1; (index < argc) && (wd >= 0); index ) 45.{ 46.wd = watch_dir (inotify_fd, argv[index], IN_ALL_EVENTS); 47.} 48.if (wd > 0) 49.{ 50./* Wait for events and process them until a 51.termination condition is detected 52.*/ 53.process_inotify_events (q, inotify_fd); 54.} 55.printf ("nTerminatingn"); 56./* Finish up by closing the fd, destroying the queue, 57.and returning a proper code 58.*/ 59.close_inotify_fd (inotify_fd); 60.queue_destroy (q); 61.} 62.return 0; 63.}
利用 inotify_init 打开文件描述符 清单 3 展示了用于创建 inotify 实例的简单应用函数,并为其获得一个文件描述符.文件描述符返回给了调用者. 如果出现错误,返回值将为负. 清单 3. 使用 inotify_init 1./* Create an inotify instance and open a file descriptor 2.to access it */ 3.int open_inotify_fd () 4.{ 5.int fd; 6.watched_items = 0; 7.fd = inotify_init (); 8.if (fd < 0) 9.{ 10.perror ("inotify_init () = "); 11.} 12.return fd; 13.} 利用 inotify_add_watch 来增加监控 有了用于 |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |