Linux C如何避免inotify_add_watch no such file or directory
时间: 2023-10-24 11:08:43 浏览: 215
要避免inotify_add_watch函数返回no such file or directory错误,需要确保要监视的目录存在。可以通过调用access或stat函数来判断目录是否存在,如果目录不存在,则可以先创建该目录。
以下是一个示例代码片段:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/inotify.h>
#include <sys/stat.h>
int main(int argc, char **argv) {
int fd, wd;
char *path = "/path/to/dir";
// 检查目录是否存在
struct stat st;
if (stat(path, &st) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
// 创建 inotify 实例
fd = inotify_init();
if (fd == -1) {
perror("inotify_init");
exit(EXIT_FAILURE);
}
// 添加监视器
wd = inotify_add_watch(fd, path, IN_ALL_EVENTS);
if (wd == -1) {
perror("inotify_add_watch");
exit(EXIT_FAILURE);
}
// 等待事件发生
// ...
// 移除监视器
inotify_rm_watch(fd, wd);
// 关闭 inotify 实例
close(fd);
return 0;
}
```
在上面的代码中,首先通过调用stat函数来检查要监视的目录是否存在。如果目录不存在,程序会输出一个错误信息并退出。如果目录存在,则继续创建inotify实例,并调用inotify_add_watch函数添加一个监视器。如果inotify_add_watch返回了no such file or directory错误,则说明要监视的目录不存在,程序会输出一个错误信息并退出。如果inotify_add_watch成功添加了监视器,则可以继续等待事件的发生。最后,需要调用inotify_rm_watch函数移除监视器,并关闭inotify实例。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)