我从互联网上的many examples那里获取了以下有关如何使用inotify的代码.
然后,我尝试了以下实验:
1)在下面运行观察程序
2)在单独的外壳中,将cd插入’/ mypath’,将其中一些文件创建到您正在观看的文件夹中.例如,“日期> output.txt”一次或多次.
3)您将看到来自观察者的通知.
4)输入’ls / mypath'(甚至是’watch -n 1 / mypath’)
5)尝试“日期> / mypath中的output.txt”.您将不再看到观察者的通知.至少,这就是我在Ubuntu 12/13上进行测试时发生的情况.
关于如何解决它的任何想法?
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <limits.h>
#include <unistd.h>
#define MAX_EVENTS 1024 /*Max. number of events to process at one go*/
#define LEN_NAME 16 /*Assuming that the length of the filename won't exceed 16 bytes*/
#define EVENT_SIZE ( sizeof (struct inotify_event) ) /*size of one event*/
#define BUF_LEN ( MAX_EVENTS * ( EVENT_SIZE + LEN_NAME )) /*buffer to store the data of events*/
int main()
{
int length, i = 0, wd;
int fd;
char buffer[BUF_LEN];
/* Initialize Inotify*/
fd = inotify_init();
if ( fd < 0 ) {
perror( "Couldn't initialize inotify");
}
/* add watch to starting directory */
wd = inotify_add_watch(fd, "/mypath", IN_CLOSE_WRITE | IN_CLOSE_NOWRITE);
if (wd == -1)
{
printf("Couldn't add watch to %s\n","/mypath");
}
else
{
printf("Watching:: %s\n","/mypath");
}
/* do it forever*/
while(1)
{
i = 0;
length = read( fd, buffer, BUF_LEN );
if ( length < 0 ) {
perror( "read" );
}
while ( i < length ) {
struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];
if ( event->len ) {
if ( event->mask & IN_CLOSE_WRITE) {
if (event->mask & IN_ISDIR)
printf( "The directory %s was Created.\n", event->name );
else
printf( "The file %s was closed (write) with WD %d\n", event->name, event->wd );
}
if ( event->mask & IN_CLOSE_NOWRITE) {
if (event->mask & IN_ISDIR)
printf( "The directory %s was Created.\n", event->name );
else
printf( "The file %s was closed (nowrite) with WD %d\n", event->name, event->wd );
}
i += EVENT_SIZE + event->len;
}
}
}
/* Clean up*/
inotify_rm_watch( fd, wd );
close( fd );
return 0;
}
解决方法:
您不应该将i = EVENT_SIZE event-> len;在if(event-> len)块中.如果事件的名称长度为零,则指针仍应增加EVENT_SIZE(如果将该语句放在块外会发生这种情况).我认为您可能会在inotify程序中看到一个无限循环,该循环由第一个恰好具有零长度名称的事件开始. (这正是ls会发生的情况:正在打开目录,而不是其文件,因此name字段中没有任何内容.)