inotify_add_watch 因没有此类文件或目录而失败

Dnj*_*Abc 5 c c++ amazon-ec2 inotify ubuntu-16.04

我正在尝试在我的 c/c++ 程序中监视文件的创建。我正在尝试使用 inotify 来实现此目的。但是,当我在代码中no such file or directory进行inotify_add_watch()调用时,我收到了。我正在 Ubuntu 16.04 机器上运行我的程序。该机器在 EC2 云中运行。有人可以告诉我收到 的可能原因no such file or directory error吗?

根据inotify_add_watch的手册页,这甚至不是可能的错误代码之一。我已确保我对要监视的文件具有适当的读取权限等。

这是我的测试程序:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <limits.h>

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

int
main(int argc, char **argv)
{
  int length, i = 0, wd;
  int fd;
  char buffer[BUF_LEN];

  /* Initialize Inotify*/
  fd = inotify_init();
  if (fd < 0) {
    perror("Couldn't initialize inotify");
  }

  /* add watch to starting directory */
  wd = inotify_add_watch(fd, argv[1], IN_CREATE | IN_MODIFY | IN_DELETE);

  if (wd == -1) {
      printf("Couldn't add watch to %s. errno=%d\n", argv[1], errno);
      return -1;
  } else {
      printf("Watching:: %s\n",argv[1]);
  }

  /* do it forever*/
  while (1) {
    i = 0;
    length = read(fd, buffer, BUF_LEN);

    if (length < 0) {
      perror("read");
    }

    while (i < length) {
      struct inotify_event *event = (struct inotify_event *) &buffer[i];
      if (event->len) {
        if (event->mask & IN_CREATE) {
          printf("Create event. file=%s, wf=%d\n", event->name, event->wd);
        }

        if (event->mask & IN_MODIFY) {
          printf("Modify event. file=%s, wf=%d\n", event->name, event->wd);
        }

        if (event->mask & IN_DELETE) {
          printf("Delete event. file=%s, wf=%d\n", event->name, event->wd);
        }

        i += EVENT_SIZE + event->len;
      }
    }
  }

  /* Clean up*/
  inotify_rm_watch(fd, wd);
  close(fd);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

小智 4

如果你想监视文件/目录的创建,你应该监视父目录,因为当你调用inotify_add_watch(). 然后,当您的监视目录中创建任何文件/目录时,您将收到一个事件,并且新的文件/目录名称将位于 event->name 中。