要监控目录的文件创建或删除,您可以创建inotify 实例并使用标志IN_CREATE | IN_DELETE 进行监控。要监视文件或目录,首先使用inotify_init 创建inotify 实例,该实例将返回一个文件描述符。然后,您可以使用inotify_add_watch 添加要监视的文件/目录,并提供适当的标志来查找所需的更改。然后,您可以简单地使用read,它将阻止直到检测到符合您标准的更改。
一个监视目录的简单示例(作为输入作为第一个参数 [./tmp 默认])如下:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/inotify.h>
#define EVENT_SIZE ( sizeof (struct inotify_event) )
#define EVENT_BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) )
int dir_exists (char *d);
int main (int argc, char **argv)
{
int length, i = 0;
int fd;
int wd;
char buffer[EVENT_BUF_LEN];
char *path = argc > 1 ? argv[1] : "./tmp";
/* check directory to monitor exists */
if (!dir_exists (path)) {
fprintf (stderr, "error: directory does not exist '%s'.\n", path);
return 1;
}
/* create inotify instance & validate */
if ((fd = inotify_init ()) < 0) {
perror ("inotify_init");
}
/* add path to inotify watch list monitor for file create, delete.
add IN_MOVED_FROM | IN_MOVED_TO or move to/from directory */
wd = inotify_add_watch (fd, path, IN_CREATE | IN_DELETE);
/* monitor path for new file creation or deletion
(read blocks until the change event occurs) */
if ((length = read (fd, buffer, EVENT_BUF_LEN)) < 0) {
perror ("read");
}
/* report name of file created or deleted */
while (i < length) {
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_CREATE) {
if (event->mask & IN_ISDIR) {
printf ("New directory %s created.\n", event->name);
} else {
printf ("New file %s created.\n", event->name);
}
} else if (event->mask & IN_DELETE) {
if (event->mask & IN_ISDIR) {
printf ("Directory %s deleted.\n", event->name);
} else {
printf ("File %s deleted.\n", event->name);
}
}
}
i += EVENT_SIZE + event->len;
}
/* remove monitoring of path from the watch list. */
inotify_rm_watch (fd, wd);
/* close the inotify instance */
close (fd);
return 0;
}
/** test that directory exists (>=1 success, 0 otherwise)
* NOTE: no directory is actually created. fail occurs instead.
*/
int dir_exists (char *d)
{
int flags = O_DIRECTORY | O_RDONLY;
int mode = S_IRUSR | S_IWUSR;
int fd = open (d, flags, mode);
if (fd < 0) /* directory does not exist */
return 0;
else if (fd) { /* directory exists, rtn fd */
close (fd);
}
return fd;
}
编译
gcc -Wall -Wextra -o bin/inotify_watch inotify_watch.c
使用示例
$ ./bin/inotify_watch &
[1] 16916
$ touch tmp/file.txt
New file file.txt created.
[1]+ Done ./bin/inotify_watch