c语言使用inotify的实例

原文链接:http://www.thegeekstuff.com/2010/04/inotify-c-program-example/

我在上面稍微做了点修改,使得可以监听多个目录,而且可以循环监听,不会监听到一个事件就停止了

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <linux/inotify.h>

#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define EVENT_BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )

int main( )
{
	int length, i = 0;
	int fd;
	int wd;
	char buffer[EVENT_BUF_LEN];

	/*creating the INOTIFY instance*/
	fd = inotify_init();

	/*checking for error*/
	if (fd < 0) {
		perror("inotify_init");
	}

	/*adding the “/tmp” directory into watch list. Here, the suggestion is to validate the existence of the directory before adding into monitoring list.*/
	wd = inotify_add_watch(fd, "/tmp", IN_CREATE | IN_DELETE);
	inotify_add_watch(fd, "/tmp/dir1", IN_CREATE | IN_DELETE);  //添加了一个子目录进行监听,默认是不会监听子目录的
	/*read to determine the event change happens on “/tmp” directory. Actually this read blocks until the change event occurs*/

	for ( ; ;)  // 在外面加了一个循环,防止监听完一个事件后就退出了
	{
		i = 0;
		length = read(fd, buffer, EVENT_BUF_LEN);

		/*checking for error*/
		if (length < 0) {
			perror("read");
		}

		/*actually read return the list of change events happens. Here, read the change event one by one and process it accordingly.*/
		while (i < length) {
			struct inotify_event *event = (struct inotify_event *) &buffer[i];
			if (event->len) {
				if (event->mask & IN_CREATE) {
					if (event->mask & IN_ISDIR) {
						printf("New directory %s created.\n", event->name);
					} else {
						printf("New file %s created.\n", event->name);
					}
				} else if (event->mask & IN_DELETE) {
					if (event->mask & IN_ISDIR) {
						printf("Directory %s deleted.\n", event->name);
					} else {
						printf("File %s deleted.\n", event->name);
					}
				}
			}
			i += EVENT_SIZE + event->len;
		}

	}
	/*removing the “/tmp” directory from the watch list.*/
	inotify_rm_watch(fd, wd);
	/*closing the INOTIFY instance*/
	close(fd);
	return 0;
}


  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值