在Ubuntu系统中,inotify
API是一组用于监控文件系统事件的接口。要使用inotify
API,你需要包含相应的头文件,并链接到正确的库。以下是一个简单的示例,展示了如何使用inotify
API来监控一个文件或目录的变化。
首先,确保你的系统已经安装了libinotify-dev
开发包,它提供了inotify
API的头文件和静态库。你可以使用以下命令来安装它:
sudo apt-get update
sudo apt-get install libinotify-dev
然后,你可以编写一个C程序来使用inotify
API。下面是一个简单的示例程序,它会创建一个inotify
实例,添加一个监控项,并等待事件发生:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <unistd.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 <path-to-watch>\n", argv[0]);
exit(EXIT_FAILURE);
}
// 创建inotify实例
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
exit(EXIT_FAILURE);
}
// 添加监控项
wd = inotify_add_watch(fd, argv[1], IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
exit(EXIT_FAILURE);
}
// 等待事件发生
while (1) {
length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
exit(EXIT_FAILURE);
}
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);
} else if (event->mask & IN_DELETE) {
printf("File %s was deleted.\n", event->name);
} else if (event->mask & IN_MODIFY) {
printf("File %s was modified.\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
i = 0;
}
// 移除监控项并关闭inotify实例
(void) inotify_rm_watch(fd, wd);
(void) close(fd);
exit(EXIT_SUCCESS);
}
将上面的代码保存到一个文件中,例如inotify_example.c
,然后使用以下命令编译它:
gcc inotify_example.c -o inotify_example
运行编译后的程序,并指定你想要监控的文件或目录:
./inotify_example /path/to/watch
程序将运行并打印出监控路径下发生的文件系统事件。
请注意,这个示例程序是一个无限循环,它会一直运行直到被外部信号终止。在实际应用中,你可能需要添加一些逻辑来优雅地处理程序的退出。