微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用于监视文件写入的正确 inotify 事件掩码配置是什么?

如何解决用于监视文件写入的正确 inotify 事件掩码配置是什么?

我正在尝试使用 inotify 来监视文件的任何读取或写入。

典型用例是用户运行以下命令之一,我会收到相应的通知

echo "xyz" > /tmp/the_file # 这应该给我写通知

cat /tmp/the_file # 这应该会给我一个访问通知

我尝试过以下面膜:

  • mask = (IN_MODIFY|IN_ACCESS); //获取正确的读取通知,写入我收到 2 个通知
  • mask = (IN_CLOSE_WRITE|IN_ACCESS); // 获取正确的读取通知,没有写入通知

为每次读取和写入获得单个通知的正确掩码值是多少?

我使用此博客中的测试应用程序作为参考: How to Use inotify API in C Language

#include<stdio.h>
#include<sys/inotify.h>
#include<unistd.h>
#include<stdlib.h>
#include<signal.h>
#include<fcntl.h>

#define MAX_EVENTS 1024
#define LEN_NAME 256
#define EVENT_SIZE  (sizeof (struct inotify_event))
#define BUF_LEN     (MAX_EVENTS * (EVENT_SIZE + LEN_NAME))

int fd,wd;
void sig_handler(int sig){
  inotify_rm_watch(fd,wd);
  close(fd);
  exit(0);
}

int main(int argc,char **argv){
  char *path_to_be_watched;
  int i=0,length;
  char buffer[BUF_LEN];
  struct inotify_event *event = (struct inotify_event *) &buffer[i];

  path_to_be_watched = argv[1];
  signal(SIGINT,sig_handler);
  fd = inotify_init();
  fcntl(fd,F_SETFL,O_NONBLOCK);
  wd = inotify_add_watch(fd,path_to_be_watched,IN_MODIFY | IN_ACCESS);

  if(wd==-1){
    printf("Could not watch : %s\n",path_to_be_watched);
  } else {
    printf("Watching : %s\n",path_to_be_watched);
  }

  while(1){
    i=0;
    length = read(fd,buffer,BUF_LEN);

    while(i<length){
      event = (struct inotify_event *) &buffer[i];

      if(event->len){
        if ( event->mask & IN_MODIFY ) {
          printf( "The file %s was modified.\n",event->name );
          /* This gets printed twice when I run 'echo "123" > /tmp/this_file' */
        }
        else if ( event->mask & IN_ACCESS ) {
          printf( "The file %s was accessed.\n",event->name );
        }
      }
      i += EVENT_SIZE + event->len;
    }
  }

  return(0);
}

echo "hello" > ./a.txt 的 strace 片段

openat(AT_FDCWD,"./a.txt",O_WRONLY|O_CREAT|O_Trunc|O_LARGEFILE,0666) = 3
fcntl64(1,F_GETFD)                     = 0
fcntl64(1,F_DUPFD,10)                 = 10
fcntl64(1,F_GETFD)                     = 0
fcntl64(10,F_SETFD,FD_CLOEXEC)        = 0
dup2(3,1)                              = 1
close(3)                                = 0
write(1,"hello\n",6)                  = 6
dup2(10,1)                             = 1
fcntl64(10,F_GETFD)                    = 0x1 (flags FD_CLOEXEC)
close(10)                               = 0

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?