3

On Linux, suppose a process opens a file for writing, something deletes the file (perhaps misconfigured log rotation), but the process keeps running, keeps the file handle open, and keeps writing to it. My understanding is that in this case, the storage used by the file still exists on disk, until the process terminates.

Suppose I want to read that file. Is there any way for another process to open the file pointed to by that file handle, or to otherwise get access to the data written to it?

James_pic
  • 3,240
  • 19
  • 24
  • 1
    As `root` you can access `/proc/PID/fd/FD`, see https://stackoverflow.com/q/18197365/10622916 or https://stackoverflow.com/q/1178593/10622916 – Bodo Aug 19 '19 at 10:51
  • @Bodo Ah, thank you. For some reason I failed to find those other questions. I guess this is a dupe then. – James_pic Aug 19 '19 at 10:57

2 Answers2

2

Yes it can. Via /proc/$pid/fd/$fd.

Example:

#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int fd;
    if(0>(fd = open("DELETED", O_CREAT|O_RDWR|O_CLOEXEC, 0600))) return perror("open"),1;
    static char const msg[]="got me\n";
    (void)write(fd, msg, sizeof(msg));
    if(0>(unlink("DELETED"))) return perror("unlink"),1;
    char buf[128];
    sprintf(buf,"cat /proc/%ld/fd/%d", (long)getpid(), fd);
    system(buf);

}

(Here I'm accessing it from a(n indirect) child process, but this is not a requirement. It works from unrelated processes as well.)

The /proc/$pid/fd/$fd items appear as symlinks in the filesystem.

They usually point to the name the file was opened as but when the file is deleted, the original link target has a " (deleted)" appended to it as in

lrwx------ 1 petr petr 64 Aug 19 12:45 /proc/32027/fd/3 -> '/home/petr/DELETED (deleted)'

yet in spite of such a target being nonexistent such a proc symlink works (through some dark kernel magic, presumably).

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
0

Suppose I want to read that file. Is there any way for another process to open the file pointed to by that file handle, or to otherwise get access to the data written to it?

As long as any process has the file open, its i-node and any other data will remain on disk. It is at least possible in principle to find that i-node and that data, and read them directly from the disk, though that's not exactly the same thing as opening the file. It may even be possible to do that after the last process closes the file -- this is how undeletion utilities work, and these do exist for Linux filesystems.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157