Linux下C语言中inotify如何获取文件全路径


=Start=

缘由:

学习提高需要

正文:

参考解答:

You’re watching a file. You have passed its name to inotify_add_watch, and got a watch descriptor. If you get an event, you can figure out the file by the watch descriptor.

You’re watching a directory. Again, you have passed the directory name to inotify_add_watch, and can find which name it was, based on the watch ID. Now inotify_event.name contains the file name. Concatenate the two and you’re done.

翻译过来就是:

  • 对于给 inotify_add_watch() 传递的参数是文件来说,当I/O事件发生时 inotify_event.name 为 NULL ;
  • 对于给 inotify_add_watch() 传递的参数是目录来说,当I/O事件发生时 inotify_event.name 为 文件名(但不包括路径) ;

在C语言中的一个解决办法就是新建一个结构体用于存放文件描述符fd和对应的传入的文件/目录名pathname(如果传给inotify_add_watch()函数的就是相对路径,且你希望获取对应的绝对路径,可以考虑用一个函数realpath()来实现这个转换):

#ifndef PATH_MAX
#define PATH_MAX 128
#endif
typedef struct {
    int fd;
    char pathname[PATH_MAX];
} inotify_fd_path;

在C++中应该是有map这样的数据结构可以实现这个功能,参考:inotify-example.cpp

参考链接:

=END=

, ,

《“Linux下C语言中inotify如何获取文件全路径”》 有 1 条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注