inotify_init使用

用于监控文件/目录的修改创建删除等操作,也可以配合epoll使用。

#include <stdio.h>
#include <stdlib.h>
#include <error.h>
#include <sys/inotify.h>
#include <string.h>
// #include <unistd.h>
#include "head.h"
#include <iostream>
using namespace std;

#define LOG_TAG "inotify_thread"
#define WATCH_PATH "/home/mi/GitLab/coding/MyProject/test.txt"
void * inotify_thread(void *) {
	int fd = -1;
	int wd = -1;
	char buf[1024] = {0};
		
	fd = inotify_init();
	if (fd < 0) {
		close(fd);
		printf("inotify_init failed!\n");
		return NULL;
	}
	wd =  inotify_add_watch(fd, WATCH_PATH, IN_MODIFY | IN_CREATE | IN_DELETE); 
	if (wd < 0) {
		close(wd);
		printf("inotify_add_watch failed!\n");
		return NULL;
	}
	static_num++;
	cout << "inotify thread static_num = " << static_num << endl;
	while (1) {
		int result = -1;
		struct inotify_event *event = NULL;
		struct inotify_event *pos_ev = NULL;
		int event_mask = 0;
		memset(buf, 0, sizeof(buf));
		printf("inotify thread reading ...\n");
		result = read(fd, buf, sizeof(buf) -1);
		if (result < (int)sizeof(struct inotify_event)) {
            printf("could not read event: %s\n",strerror(result));
            return NULL;
        }
		pos_ev = (struct inotify_event *) buf;
		while (result >= (int)sizeof(struct inotify_event)) {
			event = pos_ev;
			event_mask |= event->mask;
			printf("%s: read length = %d.\n", LOG_TAG, result);
			result -= sizeof(*event);
			pos_ev++;
		}

		switch(event_mask) {
		case IN_MODIFY:
			printf("%s: modify operation!\n", LOG_TAG);
			break;
		case IN_CREATE:
			printf("%s: create operation!\n", LOG_TAG);
			break;
		case IN_DELETE:
			printf("%s: delete operation!\n", LOG_TAG);
			break;
		default:
			printf("%s: default operation!\n", LOG_TAG);
	}
	}
	inotify_rm_watch(fd, wd);
	close(fd);
	return NULL;
}


操作文件:
在这里插入图片描述
实际输出信息:
在这里插入图片描述
可以看到删掉之后再创建和操作就不行了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值