符号链接和文件重定向
在 C++ 中,我将如何检查我们正在打开的文件是否通过符号链接重定向?这是我的文件打开器处理程序:
f=fopen(addr.c_str(), "rb");
提前致谢
In C++, how would I go about checking if a file that we are opening is being redirected through Symlinks? Here is my file opener handler:
f=fopen(addr.c_str(), "rb");
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想要查看
lstat
并检查 <struct stat
的 code>st_mode 字段 为S_IFLNK
。You want to look into
lstat
and check thest_mode
field of thestruct stat
forS_IFLNK
.如果您使用 stat(),它将自动跟随符号链接。如果您使用 fstat(),则符号链接将已被跟踪,因为文件将被打开以获取文件描述符。
在这种特殊情况下,lstat() 优于 stat() 和 fstat(),因为它不遵循符号链接。调用lstat()后,再调用open()。然而,这种方法存在固有的竞争条件问题;在调用 lstat() 和 open() 之间可能会出现另一个进程/线程/任务,并将文件更改为符号链接。
幸运的是,有一个解决方案可以解决这种竞争情况。当使用 open() 打开文件时,您可以使用标志 O_NOFOLLOW。这将告诉 open() 不要遵循符号链接(如果有)。但是,您仍然需要知道您打开的文件是否是符号链接(但未遵循)。为此,请将 open() 返回的文件描述符与 fstat() 结合使用。
希望这有帮助。
If you use stat(), it will automatically follow the symlink. If you use fstat(), the symlink will have already been followed as the file will have been opened to get the file descriptor.
lstat() is preferable over stat() and fstat() in this particular case as it does not follow the symlink. After calling lstat(), then call open(). However, there is a race condition problem inherent in this method; another process/thread/task could come along between the call to lstat() and open() and change the file to a symlink.
Fortunately, there is a solution to this race condition. When opening the file with open(), you may be able to use the flag O_NOFOLLOW. This will tell open() not to follow symlink if there is one. However, you will still need to know if the file you opened was a symlink (but not followed) or not. To do this, use the file descriptor returned from open() with fstat().
Hope this helps.