【问题标题】:What is inotify_add_watch's fd parameter?inotify_add_watch 的 fd 参数是什么?
【发布时间】:2020-12-25 03:21:05
【问题描述】:

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

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

这是什么意思?

【问题讨论】:

  • inotify_init()inotify_init1()返回的描述符...
  • 什么是描述符
  • inotify_add_watch 为您正在观看的内容创建一个文件描述符,因为路径名可以更改或删除,但只要您的程序正在运行,文件描述符就会保留一个句柄。

标签: c linux inotify


【解决方案1】:

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, 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;  

【讨论】:

  • @yanzhangguo 我还是不明白。我刚刚问了一个简单的问题,什么是 fd 参数以及为什么在inotify_add_watch 中使用它?
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    相关资源
    最近更新 更多