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

查看:112
本文介绍了从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,并确保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天全站免登陆