[Solved-6 Solutions] How to get Filename from file descriptor(Linux) in C - Linux Tutorial
Is it possible to get the filename from a file descriptor (Linux) in C ?
To get the filename from a file descriptor we can use:
/proc/self/fd/NNNwhere NNN is the file descriptor.
- The name of the file was opened — 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,
statthe filename given and
fdwe have, and make sure
st_inoare the same.
- File descriptors refer to files, and see some odd text strings, such as pipe:.
- The real filenames will be absolute paths, to determine which these are easily.
- Further, as others have noted, files can have multiple hardlinks pointing to them - this will only report the one it was opened.
- To find all names for a given file, to traverse the entire filesystem.
Read AlsoHow to Use Grep to Show just Filenames.
This problem on Mac OS X. We don't have a /proc. virtual file system.
We do, instead, have a F_GETPATH command for fcntl:
To get the file associated to a file descriptor:
- No option to do the require "directly and reliably", since a given FD may correspond to 0 filenames (in other cases) or > 1.
- Need the functionality to the limitations (on speed AND on the possibility of getting 0, 2, ... results rather than 1), we can do it: first, fstat the FD -- this tells as, in the resulting
struct stat, what device the file lives on, how many hard links it has, whether it's a special file, etc.
- For e.g. if 0 hard links to know there is in fact no corresponding filename on disk.
- If the stats to give, then we have to "walk the tree" of directories on the relevant device otherwise we find all the hard links (or just the first one, if you don't need more than one and any one will do).
- Use readdir (and opendir &c of course) recursively opening subdirectories until to find in a
struct direntthus received the same inode number you had in the original
- If this general approach is acceptable, C code, to know, hard to write (though I'd rather not write it if it's useless, i.e. you cannot withstand the inevitably slow performance or the possibility of getting != 1 result for the purposes of your application;
- Restrictions to occur but lsof seems capable of determining the file descriptor and file name. This data exists in the
/procfilesystem so it should be possible to get at from the program.
fstat() to get the file's inode by
struct stat. Then, using readdir() you can compare the inode you found with those that exist (struct dirent) in a directory and find the corresponding file name.