inotify_add_watch 的 fd 参数是什么?

问题描述

我正在开发一个监控文件夹和文件的项目,但我不知道 inotify_add_watch 是如何工作的。我在网上搜索fd 的作用,但我不明白 man page

fd 参数是一个文件描述符,引用要修改其监视列表的 inotify 实例。

这是什么意思?

解决方法

fd 是 inotify_init()inotify_init1() 的返回值。

first,use inotify_init() or inotify_init1() to initialize an inotify 
instance;
second,return a file descriptor (with a new inotify event queue) fd ;
third,use the returned fd in inotify_add_watch to monitor the file path 
you want to monitor.

示例代码:

  int fd = inotify_init();                
  int wd = inotify_add_watch(fd,argv[1],IN_ALL_EVENTS);                  
  
  for (;;) 

  {   
       fd_set fds;   
       FD_ZERO(&fds);                
       FD_SET(fd,&fds);   


       if (select(fd + 1,&fds,NULL,NULL) > 0)       

       {   
           int len,index = 0;   
           while (((len = read(fd,&buf,sizeof(buf))) < 0) && (errno == EINTR));      
           while (index < len) 

           {   
                  event = (struct inotify_event *)(buf + index);                      
                  _inotify_event_handler(event);                                             
                  index += sizeof(struct inotify_event) + event->len;             
           }   
       }   
  }   
  
  inotify_rm_watch(fd,wd);             
  
  return 0;  
,

文件描述符基本上是一些输入/输出资源的标识符。使用inotify时,需要用inotify_init初始化一个实例,它返回一个文件描述符,然后你可以用inotify_add_watch将你想看的文件添加到实例中。

因此,回答您的问题,inotify_add_watch 中的 fd 参数是由 inotify_init 调用返回的 inotify 实例的文件描述符。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...