inotify api 在报告一两次后停止工作

Ayu*_*bey 6 c select file-descriptor inotify

我想测试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 read\n");

        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=%u\n",
                    event->wd, event->mask,
                    event->cookie, event->len);

                if (event->mask & IN_MODIFY)
                printf("file modified %s", event->name);

                if (event->len)
                printf("name=%s\n", event->name);

                i += EVENT_SIZE + event->len;
             }
        }

    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

因此,我转向 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 select\n");
    //rfds = rfdss;
    ret = select (fd + 1, &rfds, NULL, NULL, NULL);
    printf("After Select\n");
    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 );
}
Run Code Online (Sandbox Code Playgroud)

Ayu*_*bey 3

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

他们实际上不是直接覆盖该文件,而是创建一个临时文件,然后用新的临时文件替换原始文件。因此,实际发生的情况是您实际观看的文件不再存在,因此所做的任何更改都不会反映回来。

实际遵循此方法的编辑器有(可能还有更多)Gedit、Geany、vi

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

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