从 C 中的文件描述符中检索文件名 [英] Retrieve filename from file descriptor in C

查看:28
本文介绍了从 C 中的文件描述符中检索文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 C 中获取文件描述符 (Linux) 的文件名?

Is it possible to get the filename of a file descriptor (Linux) in C?

推荐答案

您可以使用 readlink/proc/self/fd/NNN 上,其中 NNN 是文件描述符.这将为您提供文件打开时的名称——但是,如果文件从那时起被移动或删除,它可能不再准确(尽管 Linux 在某些情况下可以跟踪重命名).为了验证,stat 给定的文件名和 fstat 你拥有的 fd,并确保 st_devst_ino 是一样.

You can use readlink on /proc/self/fd/NNN where NNN is the file descriptor. This will give you the name of the file as it was when it was opened — however, if the file was moved or deleted since then, it may no longer be accurate (although Linux can track renames in some cases). To verify, stat the filename given and fstat the fd you have, and make sure st_dev and st_ino are the same.

当然,并不是所有的文件描述符都指向文件,对于那些你会看到一些奇怪的文本字符串,比如 pipe:[1538488].由于所有真实文件名都是绝对路径,因此您可以很容易地确定哪些是绝对路径.此外,正如其他人所指出的,文件可以有多个指向它们的硬链接 - 这只会报告打开它的那个.如果要查找给定文件的所有名称,只需遍历整个文件系统即可.

Of course, not all file descriptors refer to files, and for those you'll see some odd text strings, such as pipe:[1538488]. Since all of the real filenames will be absolute paths, you can determine which these are easily enough. Further, as others have noted, files can have multiple hardlinks pointing to them - this will only report the one it was opened with. If you want to find all names for a given file, you'll just have to traverse the entire filesystem.

这篇关于从 C 中的文件描述符中检索文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆