c++ - 使用 INotify 监视具有多个符号链接(symbolic link)的文件

标签 c++ c linux symlink inotify

所以我设置了一些代码来监视配置文件的编辑,直到我使用 VIM 编辑文件之前它一直有效,然后我还必须监视目录的重命名和创建。然后我发现在路径层次结构中没有捕捉到更高的重命名。然后我查看了符号链接(symbolic link)...gaaahhhh!

首先设置一个虚构的示例,展示一个(许多)棘手的符号链接(symbolic link)场景:

mkdir config1
touch config1/config
ln -s config1 machine1

mkdir config2
touch config2/config
ln -s config2 machine2

ln -s machine1 active

现在,给定一个我想要监视的文件名,如 active/config,我可以看到如何获取一个 inotify 监视描述符:

config1/ -> watch active/ follow symlinks (watches inode for config1)
active/ -> watch active/ dont follow symlinks (watches inode for active symlink
active/config -> watch active/config (watches inode for config1/config)

如何在 machine1 符号链接(symbolic link)上添加监视?我是否需要找到某种方法来手动遍历每个符号链接(symbolic link),并沿途为每个符号链接(symbolic link)添加监视?怎么办?

目的是允许:

mkdir config3
touch config3/config
ln -s -f -n config3 machine1

并让 inotify 警告 active/config 已被重定向。目前看来我必须添加 watch :

- target file inode
- every directory inode leading to the file (to detect moves/renames of directories)
- every symlink inode involved in reaching any of the above

必须有一种更简单的方法来只观看一个文件吗?是我偏离了道路还是真的如此?

最佳答案

我的回答是直截了当的“是的,你做得对”。

仔细阅读后inotify syscall manpage ,我看不出除了监视(可能是符号链接(symbolic link)的)文件路径的每一步以检测对完整路径的任何和所有更改之外的任何方法。

这似乎就是 inotify 的工作方式:它只查看特定的文件或文件夹,它自己不进行递归。那,再加上必须明确遵循符号链接(symbolic link),似乎符合您的三步计划。

手册页中的精选引述:

The following further bits can be specified in mask when calling inotify_add_watch(2): IN_DONT_FOLLOW (since Linux 2.6.15)

Don't dereference pathname if it is a symbolic link.

[...]

Limitations and caveats

Inotify monitoring of directories is not recursive: to monitor subdirectories under a directory, additional watches must be created. This can take a significant amount time for large directory trees. [...]

FAQ还为您的策略重新符号链接(symbolic link)提供支持:

Q: What about the IN_ONLYDIR and IN_DONT_FOLLOW flags? IN_ONLYDIR ensures that the event occur only on a directory. If you create such watch on a file it will not emit events. IN_DONT_FOLLOW forbids following symbolic links (these ones will be monitored themselves and not the files they point to).

关于c++ - 使用 INotify 监视具有多个符号链接(symbolic link)的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28769503/

相关文章:

c++ - 调用复制 ctor 和另一个 ctor

c - 如果程序在断点处停止,套接字会发生什么行为?

c - 显式 int32 -> float32 转换的规则

c - 多个客户端未连接且无法同时通信

c++ - 垃圾收集的概念与非 OOP 语言有何关系

c++ - 在类中使用 static_assert - 如何?

c++ - 如何在 Visual Studio 中使用 C++11 线程

linux - 为什么ELF magic number中没有16位信息?

c++ - OpenCL——不同设备上的不同内核 "printf()"结果?

linux - 如何使用 mogrify 裁剪图像