文件和文件夹管理 - 监视文件事件

2019-09-26  本文已影响0人  无无吴

Linux提供了一个接口inotify来监视文件,比如说监视他们什么时候移动,从哪里被读,写,或删除。

初始化 inotify

#include <sys/inotify.h>
int inotify_init1(int flags);

flag通常为0。
成功返回一个代表初始化实例的fd, 失败返回-1并设置errno。

int  fd;
fd = inotify_init1(0);
if(fd == -1){
      perror("inotity_init1");
      exit(EXIT_FAILURE);
}

监视watch

添加一个新的watch

#include <sys/inotify.h>
int inotify_add_watch(int fd, const char *path, uint32_t mask);

成功返回一个新的watch描述符,失败返回-1并且设置errno。

watch masks

多个inotify event之间是或的关系。

int wd;
wd = inotify_add_watch (fd, "/etc", IN_ACCESS | IN_MODIFY);
if (wd == −1) {
      perror ("inotify_add_watch");
      exit (EXIT_FAILURE);
}

示例为/etc的所有读或写添加一个watch。 如果/etc 中的任何文件被写入或读取,inotify 将事件发送给文件描述符fd。

inotify Events

#include <sys/inotify.h>
struct inotify_event {
        int wd; /* watch descriptor */
        uint32_t mask; /* mask of events */
        uint32_t cookie; /* unique cookie */
        uint32_t len; /* size of 'name' field */
        char name[]; /* nul-terminated name */
};

Reading inotify events

char buf[BUF_LEN] __attribute__((aligned(4)));
ssize_t len, i = 0;
/* read BUF_LEN bytes' worth of events */
len = read (fd, buf, BUF_LEN);
/* loop over every read event until none remain */
while (i < len) {
          struct inotify_event *event = (struct inotify_event *) &buf[i];
          printf ("wd=%d mask=%d cookie=%d len=%d dir=%s\n",event->wd, event->mask,event->cookie, event->len, (event->mask & IN_ISDIR) ? "yes" : "no");
/* if there is a name, print it */
if (event->len)
           printf ("name=%s\n", event->name);

Advanced inotify events

In addition to the standard events, inotify can generate other events:

Any watch can generate these events; the user need not set them explicitly.

if (event->mask & IN_ACCESS)
        printf ("The file was read from!\n");
if (event->mask & IN_UNMOUNTED)
        printf ("The file's backing device was unmounted!\n);
if (event->mask & IN_ISDIR)
        printf ("The file is a directory!\n");

Advanced WatchOptions

int wd;
/*
 * Watch '/etc/init.d' to see if it moves, but only if it is a
 * directory and no part of its path is a symbolic link.
 */
wd = inotify_add_watch (fd,"/etc/init.d",
                                          IN_MOVE_SELF |
                                          IN_ONLYDIR |
                                          IN_DONT_FOLLOW);
if (wd == −1)
        perror ("inotify_add_watch");

Removing an inotify Watch

#include <inotify.h>
int inotify_rm_watch (int fd, uint32_t wd);
int ret;
ret = inotify_rm_watch (fd, wd);
if (ret)
      perror ("inotify_rm_watch");

成功返回0,失败返回-1,并设置errno。

Obtaining the Size of the Event Queue

unsigned int queue_len;
int ret;
ret = ioctl (fd, FIONREAD, &queue_len);
if (ret < 0)
    perror ("ioctl");
else
    printf ("%u bytes pending in queue\n", queue_len);

Destroying an inotify Instance

int ret;
/* 'fd' was obtained via inotify_init() */
ret = close (fd);
if (fd == −1)
    perror ("close");
上一篇 下一篇

猜你喜欢

热点阅读