Linux: Recover Deleted File That Is Still Open

Objective: A file has been accidentally deleted on Linux but another process still has the file open. Restore or recover the file using /proc filesystem.

On Linux, files are links to an inode that contains all of the file’s properties, such as permissions and ownership, as well as the addresses of the data blocks where the file’s content is stored on disk. When a file is removed from the filesystem, only the link that points to its inode is removed and not the inode itself. In other words, the contents of the inode is not removed but merely marked as free.

Even if a file has been deleted, other processes might still have that file open. Only when all of these processes have closed the file descriptors and all links are removed that an inode and the data blocks (belonging to the deleted file) are marked as available for writing.

So, even if a file has been deleted but if a process still has the file open, the file can still be recovered using the /proc filesystem.

Let’s now go through an example. Assume that you are working on a file called “mitm.flows”.

On another terminal, delete the file using rm.

Now, the cat command still has the file opened. Get the process ID of the cat command by either using ps or lsof commands. Note that if the cat command has closed the file, then we will not be able to recover the file anymore.

The process ID of the cat command is 3215. To prevent the cat process from running and closing the file, you can send a STOP signal to the cat process. This is optional.

The above command will suspend the cat process and put it as a background job. The background job can be checked in the shell where the cat command was executed.

Now, check the file descriptors for this process in the /proc directory.

We can see that file descriptor (fd) 3 is pointing to the deleted file. To recover the file, use the following cp command.

The file will now be recovered in the directory specified in the destination.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }