【发布时间】:2014-03-14 06:30:17
【问题描述】:
我从互联网上的many examples 中获取了关于如何使用inotify 的以下代码。
然后我尝试了以下实验:
1) 在下面运行观察者
2) 在一个单独的外壳中,cd 进入'/mypath' 为您正在观看的文件夹创建一些文件。例如,'date > output.txt' 一次或多次。
3) 您将看到来自观察者的通知。
4)输入'ls /mypath'(甚至'watch -n 1 /mypath')
5) 在/mypath 中尝试'date > 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;
}
【问题讨论】:
-
您可以尝试使用
inotifywait命令行(对于inotify-tools包中的ubuntu)而不是您自己的可执行文件吗? -
不要忘记通过点击您所选答案的勾下的 +200 来奖励赏金!