[Solved-6 Solutions] How to get Filename from file descriptor(Linux) in C - Linux Tutorial
Problem:
Is it possible to get the filename from a file descriptor (Linux) in C ?
Solution 1:
To get the filename from a file descriptor we can use:
Solution 2:
-
/proc/self/fd/NNN
where 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,
stat
the filename given andfstat
thefd
we have, and make surest_dev
andst_ino
are the same. - File descriptors refer to files, and see some odd text strings, such as pipe:[1538488].
- 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 Also
How to Use Grep to Show just Filenames.Solution 3:
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:
Solution 4:
- 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 dirent
thus received the same inode number you had in the originalstruct stat
. - 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;
Solution 5:
- Restrictions to occur but lsof seems capable of determining the file descriptor and file name. This data exists in the
/proc
filesystem so it should be possible to get at from the program.
Solution 6:
Use 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.