Eran Medan Eran Medan - 3 months ago 8
C Question

How to delete a file in Linux where all I have is the file descriptor

I have an

int
file descriptor that was opened earlier (via
open
) and I need to remove that file.

Do I really have to first get the file name and call
remove
?
(e.g. via using the technique in Getting Filename from file descriptor in C)

Or is there some other (linux specific OK) way of doing it solely based on the file descriptor?

I have searched and the best I could find is the above answer.

vz0 vz0
Answer

You can use /proc to see which path an open fd is linked to, and realpath get the full path of the symlink.

# ls -l /proc/8701/fd
total 0
lr-x------ 1 root root 64 Apr 23 22:44 0 -> /dev/null
lrwx------ 1 root root 64 Apr 23 22:44 1 -> /dev/null
lrwx------ 1 root root 64 Apr 23 22:44 2 -> /dev/null
lrwx------ 1 root root 64 Apr 23 23:19 20 -> socket:[16204]
lrwx------ 1 root root 64 Apr 23 23:19 21 -> socket:[16205]
lrwx------ 1 root root 64 Apr 23 22:44 3 -> socket:[18743]
l-wx------ 1 root root 64 Apr 23 22:44 4 -> /var/lib/dhcp/dhclient-7a30dd46-5058-47aa-b71e-ff77cfbe4194-wlan0.lease
lrwx------ 1 root root 64 Apr 23 22:44 5 -> socket:[16872]
lrwx------ 1 root root 64 Apr 23 22:44 6 -> socket:[18747]