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

时间:2014-09-09 12:27:28

标签: c++ linux filesystems

我正在尝试使用inotify以递归方式监视目录。我在我的应用程序中使用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 );
     }
    }
   }
  }

1 个答案:

答案 0 :(得分:1)

发现问题。当我删除其中包含子目录的目录时,还收到了IN_DELETE_SELF事件以及IN_DELETE事件,我在IN_DELETE_SELF事件中关闭了我正在监视的目录的fd。所以现在当再次调用select时找不到fd并给了我那个错误。