当inotify的IN_DELETE事件发生时,select方法失败

select method fails when IN_DELETE event of inotify occurs

本文关键字:select 失败 方法 事件 inotify IN DELETE      更新时间:2023-10-16

我正试图使用inotify在Linux上递归地监视一个目录。我在应用程序中使用select方法来监视目录更改。除删除外,我收到所有事件的通知。当我使用rm命令删除目录时,我的select方法会失败。

我得到以下错误"无效或不完整的多字节或宽字符"

我怎样才能解决这个问题。

感谢的回复

fd  = inotify_init();
struct timeval time;
fd_set rfds;
int ret;
/* timeout after five seconds */
time.tv_sec = 5;
time.tv_usec = 0;
/* zero-out the fd_set */
FD_ZERO (&rfds);
/*
 * add the inotify fd to the fd_set -- of course,
 * your application will probably want to add
 * other file descriptors here, too
 */
FD_SET (fd, &rfds);
ret = select (fd + 1, &rfds, NULL, NULL, &time);
if (ret < 0)
        perror ("select");
else if (!ret)
        /* timed out! */
else if (FD_ISSET (fd, &rfds)
        /* inotify events are available! */
   {
       // inotify events are available
    len = read(fd, buf, EVENT_BUF_LEN);
    if(len <= 0)
    {
        qDebug()<<"Error : read failed..";
        perror("read : ");
    }
    while(i < len)
    {
        struct inotify_event *event;
        event = (struct inotify_event *) &buf[i];
        eventNotification(event);
        i += EVENT_SIZE + event->len;
        count++;
    }
  }
  void eventNotification (struct inotify_event *event)
  {
      if ( event->len )
{
   if ( event->mask & IN_CREATE )
   {
     if ( event->mask & IN_ISDIR )
     {
       printf( "The directory %s was created.n", event->name );
     }
     else
     {
       printf( "The file %s was created.n", event->name );
     }
   }
   else if ( event->mask & IN_DELETE )
   {
     if ( event->mask & IN_ISDIR )
     {
       printf( "The directory %s was deleted.n", event->name );
     }
     else
     {
       printf( "The file %s was deleted.n", event->name );
     }
   }
   else if ( event->mask & IN_MODIFY )
   {
     if ( event->mask & IN_ISDIR )
     {
       printf( "The directory %s was modified.n", event->name );
     }
     else
     {
       printf( "The file %s was modified.n", event->name );
     }
    }
   }
  }

发现问题。当我删除了一个包含子目录的目录时,in_DELETE_SELF事件和in_DELETE事件也被接收到,并且我正在关闭in_DELETE_SELF事件中我正在监视的目录的fd。所以现在当再次调用select时,找不到fd,并给了我这个错误。