在Ubuntu系统中,inotify API用于监控文件系统事件,如文件的创建、删除、修改等。要正确调用inotify API,你需要遵循以下步骤:
-
包含必要的头文件:
#include#include #include #include -
初始化inotify实例: 使用
inotify_init()函数来创建一个inotify实例。int fd = inotify_init(); if (fd < 0) { perror("inotify_init"); exit(EXIT_FAILURE); } -
添加监控: 使用
inotify_add_watch()函数来添加对特定文件或目录的监控。int wd = inotify_add_watch(fd, "/path/to/file_or_directory", IN_MODIFY | IN_CREATE | IN_DELETE); if (wd < 0) { perror("inotify_add_watch"); close(fd); exit(EXIT_FAILURE); } -
读取事件: 使用
read()函数从inotify文件描述符中读取事件。char buffer[4096]; ssize_t length = read(fd, buffer, sizeof(buffer)); if (length < 0) { perror("read"); close(fd); exit(EXIT_FAILURE); } // 解析buffer中的事件 -
解析事件:
inotify事件存储在缓冲区中,需要解析这些事件以获取详细信息。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实例: 当不再需要监控时,使用
inotify_rm_watch()函数移除监控,并使用close()函数关闭inotify文件描述符。inotify_rm_watch(fd, wd); close(fd);
示例代码
以下是一个完整的示例代码,展示了如何使用inotify API监控文件的变化:
#include
#include
#include
#include
#include
int main() {
int fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
exit(EXIT_FAILURE);
}
int wd = inotify_add_watch(fd, "/path/to/file_or_directory", IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
close(fd);
exit(EXIT_FAILURE);
}
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;
}
请将/path/to/file_or_directory替换为你想要监控的实际文件或目录路径。这个示例程序会持续运行,直到你手动终止它。
以上就是关于“Ubuntu inotify API如何正确调用”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm