Linux的inotify API允许应用程序监控文件系统事件,如文件的创建、删除、修改等。以下是使用inotify API的基本步骤:
包含必要的头文件:
#include <sys/inotify.h>
创建inotify实例:
使用inotify_init()函数创建一个inotify实例。
int fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
return -1;
}
添加监控:
使用inotify_add_watch()函数添加一个监控项。你需要指定inotify实例的文件描述符、要监控的文件或目录的路径,以及你感兴趣的事件。
int wd = inotify_add_watch(fd, "/path/to/directory", IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
close(fd);
return -1;
}
读取事件:
使用read()函数从inotify实例中读取事件。事件会被存储在一个inotify_event结构体数组中。
char buffer[4096];
ssize_t length = read(fd, buffer, sizeof(buffer));
if (length < 0) {
perror("read");
close(fd);
return -1;
}
int i = 0;
while (i < length) {
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_CREATE) {
printf("File %s was created.\n", event->name);
}
if (event->mask & IN_DELETE) {
printf("File %s was deleted.\n", event->name);
}
if (event->mask & IN_MODIFY) {
printf("File %s was modified.\n", event->name);
}
}
i += sizeof(struct inotify_event) + event->len;
}
移除监控:
当不再需要监控时,使用inotify_rm_watch()函数移除监控项。
inotify_rm_watch(fd, wd);
关闭inotify实例:
最后,使用close()函数关闭inotify实例。
close(fd);
以下是一个完整的示例程序,监控指定目录中的文件创建、删除和修改事件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
int fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
return 1;
}
int wd = inotify_add_watch(fd, argv[1], IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
close(fd);
return 1;
}
printf("Monitoring directory %s for events...\n", argv[1]);
char buffer[4096];
while (1) {
ssize_t length = read(fd, buffer, sizeof(buffer));
if (length < 0) {
perror("read");
break;
}
int i = 0;
while (i < length) {
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_CREATE) {
printf("File %s was created.\n", event->name);
}
if (event->mask & IN_DELETE) {
printf("File %s was deleted.\n", event->name);
}
if (event->mask & IN_MODIFY) {
printf("File %s was modified.\n", event->name);
}
}
i += sizeof(struct inotify_event) + event->len;
}
}
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
编译并运行这个程序:
gcc -o monitor monitor.c
./monitor /path/to/directory
这个程序会持续监控指定目录,并在检测到文件创建、删除或修改事件时打印相应的消息。