C - notify API在报告一次或两次后停止工作



我想测试inotify,所以从互联网上拿了几个例子,修改它来学习各个方面,但失败了,因为它没有像我想要的那样工作。首先,我试图监视一个目录,它工作得很好。

所以我扩展了这个例子的文件进行了一些修改,但它只工作一次,并在读取函数

时被阻塞
#include <sys/inotify.h>
#include <unistd.h>
#include <stdio.h>
#define EVENT_SIZE  (sizeof (struct inotify_event))
#define BUF_LEN        (16 * (EVENT_SIZE + 16))
int main()
{
    int fd;
    fd = inotify_init();
    if (fd < 0)
        perror("inotify_init()");
        int wd;
        wd = inotify_add_watch(fd, "target", IN_CLOSE_WRITE);
    if (wd < 0)
        perror("inotify_add_watch");
    char buf[BUF_LEN];
    int len;
    while(1) {
         len = read(fd, buf, BUF_LEN);
         printf("after readn");
        if (len > 0)
        {
            int i = 0;
            while (i < len)
            {
                struct inotify_event *event;
                event = (struct inotify_event *) &buf[i];
                printf("wd=%d mask=%x cookie=%u len=%un",
                    event->wd, event->mask,
                    event->cookie, event->len);
                if (event->mask & IN_MODIFY)
                printf("file modified %s", event->name);
                if (event->len)
                printf("name=%sn", event->name);
                i += EVENT_SIZE + event->len;
             }
        }
    }
    return 0;
}

所以,我转移到select(),但这里也,它工作一次,报告两次,然后停止报告更改。

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/inotify.h>
#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )
int main( int argc, char **argv ) 
{
int length, i = 0;
int fd;
int wd;
char buffer[BUF_LEN];
struct timeval timeout;
fd = inotify_init();
if ( fd < 0 ) {
   perror( "inotify_init" );
}
wd = inotify_add_watch( fd, "target", 
                      IN_CLOSE_WRITE );
fd_set rfds,rfdss;
int ret;
/* zero-out the fd_set */
FD_ZERO (&rfds);
FD_ZERO (&rfdss);
FD_SET (fd, &rfds);
timeout.tv_sec = 5;    
timeout.tv_usec = 0;
while(1){
    printf("Before selectn");
    //rfds = rfdss;
    ret = select (fd + 1, &rfds, NULL, NULL, NULL);
    printf("After Selectn");
    timeout.tv_sec = 5;     
    timeout.tv_usec = 0; 
    if (ret < 0)
            perror ("select");
    else if (!ret){
    }
            /* timed out! */
    else if (FD_ISSET (fd, &rfds)){
            printf("file changed============n");
            length = read( fd, buffer, BUF_LEN );
    }
}
  ( void ) inotify_rm_watch( fd, wd );
 ( void ) close( fd );
 exit( 0 );
}

一些研究表明,流行的编辑器以不同的方式保存它。

不是直接覆盖该文件,而是创建一个临时文件,然后用新的临时文件替换原文件。因此,实际发生的情况是,您实际上正在查看的文件不再存在,因此任何将要进行的更改都不会反射回来。

实际上遵循此方法的编辑器是(可能存在更多)编辑,编辑,vi

直接覆盖文件的编辑器是(可能存在更多)纳米

因此,即使代码是正确的,编辑器的异常行为也可能是有问题的

对于阻塞读调用,请参见:https://stackoverflow.com/a/914520/149111

你可能还想从IN_CLOSE_WRITE切换到IN_ALL_EVENTS,以确保你没有错过什么;可能是删除:

最佳实践是观察包含感兴趣的文件的目录,而不是单个文件,因为这将在内核中消耗更少的资源。它还允许您观察"原子"文件替换操作,其中写入器在文件系统上创建临时文件(可能在同一目录中),写入临时文件,然后在最后rename(2)将其移到原始文件的顶部。
这种替换方式确保文件的观察者只会注意到文件的完整内容,而不是它的半写版本。

最新更新