【发布时间】:2014-06-21 13:38:50
【问题描述】:
我目前正在使用 inotify() 系统在我的 C 代码中监视文件系统中某些目录的活动。
现在,使用这些东西之一的过程如下。你取一个整数(比如 event_notifier),使用 inotify_init() 把它变成一个 inotify 描述符,就像这样
event_notifier=inotify_init();
现在,假设我想监视多个目录上的事件。然后,我将通过这些目录将监视添加到这个 event_notifier
wd1 = inotify_add_watch(event_notifier,"/../path..to..directory1/../",IN_ALL_EVENTS);
wd2 = inotify_add_watch(event_notifier,"/../path..to..directory2/../",IN_ALL_EVENTS);
wd3 = inotify_add_watch(event_notifier,"/../path..to..directory3/../",IN_ALL_EVENTS);
. . . .
wdn = inotify_add_watch(event_notifier,"/../path..to..directoryn/../",IN_ALL_EVENTS);
现在,我可以在多个目录中添加监视。这些调用中的每一个都返回一个“监视描述符”(上面的 wd1、wd2、wd3.. wdn)。每当任何目录中发生事件时,inotify 系统都会向 inotify 文件描述符 event_notifier 发送一个事件以及与该特定“监视目录”相对应的监视描述符(wd1,wd2...wdn)
当一个事件进来时,我可以读取 struct inotify_event 数组的 event_notifier。这个 inotify_event 结构有以下字段:
struct inotify_event
{
int wd; //Watch descriptor
...
uint32_t len; //Size of 'name' field
char name[]; //null terminated name
}
要读取事件,您只需这样做
read(event_notifier, buffer, sizeof(buffer))
struct inotify_event* event;
event=(struct inotify_event*)buffer; //Assuming only one event will occur
我有兴趣找出通知来自哪个目录。但是当我 stat() 监视描述符时,它什么也没给我
struct stat fileinfo;
fstat(event->wd, &fileinfo);
printf("\n Size of file is %l",fileinfo_st.size);
甚至 /proc/self/fd/event->fd 上的 readlink() 也没有产生任何文件名。
char filename[25];
readlink("/proc/self/fd/event-wd",filename,sizeof(filename));
printf("\n The filename is %s",filename);
我有两个问题:
1) 监视描述符到底指向什么? 它有什么好处?
2) 我如何知道通知来自哪个目录?
【问题讨论】: