inotify不会将vim编辑视为修改事件

Hai*_*ang 4 linux vim inotify

我下面的示例代码监视文件以进行修改.假设正在进行wathched的文件是foo.txt,并且示例代码中出现的二进制名称是inotify.我为示例代码做了两次测试.

test1:
1)./inotify foo.txt
2)echo"hello"> foo.txt
然后一切正常,并且打印出" 文件修改 ".

test2:
1)./infity foo.txt
2)vim foo.txt
3)以某种方式编辑并保存,但不要退出vim
打印出来的行是 未知掩码0x00008000,签出了inotify头文件,发现此事件掩码意味着IN_CLOSE_WRITE.

从我的角度来看,"编辑并保存"只是修改了menas.但是很明显,inotify代码对它有不同的interpration.这对我来说很奇怪,任何人都可以帮忙解释背后的事情吗?

#include <sys/inotify.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>


int main(int argc, char **argv)
{
  int fdnotify = -1; 

  if (argc !=2) {
    fprintf(stderr, "usage: ./inotify dir_name\n");
    exit(1);
  }

  printf("argc is %d\n", argc);

  fdnotify = inotify_init();
  if (fdnotify < 0) {
    fprintf(stderr, "inotity_init failed: %s\n", strerror(errno));
  }

  int wd = inotify_add_watch(fdnotify, argv[1], IN_MODIFY);
  if (wd < 0) {
    fprintf(stderr, "inotify_add_watch failed: %s\n", strerror(errno));
  }

  while(1) {
    char buffer[4096];
    struct inotify_event *event = NULL;

    int len = read(fdnotify, buffer, sizeof(buffer));

    if (len < 0) {
      fprintf(stderr, "read error %s\n", strerror(errno));
    }   

    event = (struct inotify_event *) buffer;

    while(event != NULL) {
      if ((event->mask & IN_MODIFY)  ) { 
        printf("File modified %s\n", event->name);
      } else {
 printf("unknown Mask 0x%.8x\n", event->mask);
      }
      len -= sizeof(*event) + event->len;

      if (len > 0)
        event = ((void *) event) + sizeof(event) + event->len;
      else
        event = NULL;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Flo*_*ciu 6

Vim是一个在保存文件时不直接保存到文件的程序.它创建一个通常命名的临时文件,.filename.swp并且只有在关闭vim时才会将此文件重命名为filename.来自inotify的常见问题解答:

IN_MODIFY事件在文件内容更改时发出(例如,通过write()系统调用),而在关闭更改的文件时发生IN_CLOSE_WRITE.这意味着每个更改操作都会导致一个IN_MODIFY事件(在打开文件的操作期间可能会多次发生),而IN_CLOSE_WRITE只发出一次(在关闭文件时).

所以你得到的事件实际上是有道理的.假设您有一个名为的文件filename.当您打开filename文件时,会创建另一个名为的文件.filename.swp.如果受到监视,您对此文件执行的所有修改都将生成许多IN_MODIFY事件.当您实际保存时,最终发生的事情是,vim重命名此文件并关闭它,从而生成IN_CLOSE_WRITE事件.