inotify 监听文件系统事件

1 分钟读完

Just record.

iproute2

在分析 ip netns 的实现时,发现它是通过对文件系统的操作实现操纵 netns,如

ip netns list

就是遍历目录 /var/run/netns/

ip netns add 1
  • 创建 /var/run/netns/1
  • 隔离进程执行环境 unshare
  • 挂载到 /proc/self/ns/net

    ip netns monitor

监听目录 /var/run/netns/ 创建和删除事件,具体怎么实现的,非常简单

inotify

inotify - monitoring filesystem events.
The inotify API provides a mechanism for monitoring filesystem events. Inotify can be used to monitor individual files, or to monitor directories. When a directory is monitored, inotify will return events for the directory itself, and for files inside the directory.

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

#define MONITOR_PATH    "/var/onestraw/"
#define MONITOR_MASK    IN_CREATE | IN_DELETE | IN_ACCESS | IN_MODIFY

inline void _err(const char *str)
{
	perror(str);
	exit(1);
}

inline void inotify_loop(int fd)
{
	char buf[4096];
	size_t len;
	struct inotify_event *event;
	while (1) {
		len = read(fd, buf, sizeof(buf));
		if (len < 0) {
			_err("read() failed");
		}
		for (event = (struct inotify_event *)buf;
		     (char *)event < &buf[len];
		     event =
		     (struct inotify_event *)((char *)event + sizeof(*event) +
					      event->len)) {
			if (event->mask & IN_CREATE)
				printf("add %s\n", event->name);
			if (event->mask & IN_DELETE)
				printf("delete %s\n", event->name);
			if (event->mask & IN_ACCESS)
				printf("access %s\n", event->name);
			if (event->mask & IN_MODIFY)
				printf("modify %s\n", event->name);
		}
	}
}

int main(int argc, char *argv[])
{
	int fd;

	if ((fd = inotify_init()) < 0) {
		_err("inotify_init() failed");
	}
	//if (inotify_add_watch(fd, argv[1], MONITOR_MASK) < 0) {
	if (inotify_add_watch(fd, MONITOR_PATH, MONITOR_MASK) < 0) {
		_err("inotify_add_watch() failed");
	}

	inotify_loop(fd);
	return 0;
}

参考

  • iproute2
  • man7.org

标签:

分类:

更新时间:

留下评论