inotify 是 Linux 内核提供的一种文件系统事件监控机制,它可以用来监控文件或目录的变化,如打开、关闭、修改、移动等。在开发中,你可以使用 inotify 来实现各种功能,比如自动重新加载配置文件、同步文件、监控日志文件的变化等。
以下是使用 inotify 的基本步骤:
包含头文件:
在你的 C 程序中,你需要包含 sys/inotify.h 头文件来使用 inotify 相关的函数和宏。
创建 inotify 实例:
使用 inotify_init() 函数创建一个 inotify 实例,返回一个文件描述符。
添加监控:
使用 inotify_add_watch() 函数来添加你想要监控的文件或目录。你需要提供 inotify 实例的文件描述符、要监控的文件或目录的路径,以及你感兴趣的事件类型。
读取事件:
使用 read() 系统调用从 inotify 文件描述符读取事件。事件会被存储在一个 inotify_event 结构体中。
处理事件: 根据读取到的事件类型,执行相应的操作。
移除监控:
当不再需要监控时,使用 inotify_rm_watch() 函数移除监控。
关闭 inotify 实例:
最后,使用 close() 系统调用关闭 inotify 实例的文件描述符。
下面是一个简单的示例代码,演示了如何使用 inotify 监控一个文件的变化:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/inotify.h>
#define EVENT_SIZE ( sizeof (struct inotify_event) )
#define BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) )
int main(int argc, char **argv)
{
int length, i = 0;
int fd;
int wd;
char buffer[BUF_LEN];
// 检查命令行参数
if (argc != 2) {
printf("Usage: %s <filename>\n", argv[0]);
exit(1);
}
// 创建 inotify 实例
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
exit(1);
}
// 添加监控
wd = inotify_add_watch(fd, argv[1], IN_MODIFY);
if (wd < 0) {
perror("inotify_add_watch");
exit(1);
}
// 读取事件
while (1) {
length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
exit(1);
}
while (i < length) {
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_MODIFY) {
printf("File %s modified\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
i = 0;
}
// 移除监控和关闭 inotify 实例的代码没有包含在内,因为上面的循环是无限的
return 0;
}
请注意,上面的代码是一个无限循环,它会一直运行并监控文件的变化。在实际应用中,你可能需要添加一些逻辑来优雅地处理程序的终止。
此外,inotify 有监控数量的限制,可以通过 sysctl 命令查看和修改这些限制。例如,你可以使用 sysctl fs.inotify.max_user_watches 来查看当前用户可以监控的最大文件数量。如果需要,可以使用 sysctl -w fs.inotify.max_user_watches=<new-limit> 来增加这个限制。