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

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


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/fdtotal 0lr-x------ 1 root root 64 Apr 23 22:44 0 -> /dev/nulllrwx------ 1 root root 64 Apr 23 22:44 1 -> /dev/nulllrwx------ 1 root root 64 Apr 23 22:44 2 -> /dev/nulllrwx------ 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.leaselrwx------ 1 root root 64 Apr 23 22:44 5 -> socket:[16872]lrwx------ 1 root root 64 Apr 23 22:44 6 -> socket:[18747]


I don't know of any function that can remove a file based on a file descriptor, but any such function would first have to get the path anyway, and then call unlink.

A file descriptor on Linux is an association between a process and a directory entry. The directory entry is a link between a path (file name) and an inode. There can be many file descriptors associated with a directory entry, and many directory entries associated with an inode.

When you unlink a file, you are removing a link between the directory entry and the inode. If that is the last link, the file is finally removed from disk (i.e. the inode is returned to the free list, and the blocks used by the inode are also freed).


Depending on your use-case, if the file content is unwanted (ie. too large or could be harmful) you can use the fd to shrink the file to 0 bytes.

ftruncate(fd, 0);