[英]inotify_add_watch fails with no such file or directory
I am trying to watch for the creation of file in my c/c++ program.我正在尝试在我的 c/c++ 程序中观察文件的创建。 I am trying to use inotify for this purpose.
我正在尝试为此目的使用 inotify。 However, I am getting a
no such file or directory
when I make the inotify_add_watch() call in my code.但是,当我在代码中调用inotify_add_watch()时,我没有得到
no such file or directory
。 I am running my program on an Ubuntu 16.04 machine.我在 Ubuntu 16.04 机器上运行我的程序。 The machine is running in the EC2 cloud.
该机器正在 EC2 云中运行。 Can someone tell me the possible reasons for receiving a
no such file or directory error
?有人能告诉我收到
no such file or directory error
的可能原因吗?
According to the man page for inotify_add_watch , that's not even one of the possible error codes.根据inotify_add_watch的手册页,这甚至不是可能的错误代码之一。 I've made to sure I have proper read permissions for the file I am trying to monitor etc.
我已经确保我对要监视的文件等具有适当的读取权限。
Here's my test program:这是我的测试程序:
#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;
}
If you want to monitor the creation of file/directory, you should watch the parent directory since the new file/directory does not exist when you calls inotify_add_watch()
.如果要监视文件/目录的创建,则应监视父目录,因为调用
inotify_add_watch()
时新文件/目录不存在。 Then when any file/directory is created in your watching directory, you will get a event, and the new file/direcotry name will be in event->name.然后当你的监视目录中创建任何文件/目录时,你会得到一个事件,新的文件/目录名称将在 event->name 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.