获取文件名从文件描述符使用C [英] Getting Filename from file descriptor in C

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

问题描述

是否有可能得到一个文件描述符(Linux)在C 2的文件名

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

推荐答案

您可以使用 的readlink 的/ proc /自/ FD / NNN 其中NNN是文件描述符。这会给你的文件的名称,因为它是当它被打开了 - 但是如果文件移动或自那以后被删除,它可能不再是准确的(虽然Linux可以跟踪命名在某些情况下)。为了验证,统计给出的文件名和 FSTAT 你有,并确保FD st_dev st_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.

当然,并不是所有的文件描述符引用文件,并为那些你会看到一些奇怪的文本字符串,如管:[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天全站免登陆