Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file still exists using a file descriptor

I have a file descriptor that is set to a positive value with the result of a open() function so this fd is indicating a file. When i delete the actual file fd is still a positive integer. I want to know that if i delete a file for some reason, how can i know that this file descriptor is not valid anymore. In short, how can i know that the file that fd is indicating, still there or not. I am trying to do this in C on FreeBSD.

like image 280
Hasan Bozok Avatar asked Mar 21 '13 09:03

Hasan Bozok


2 Answers

Unix systems let you delete open files (or rather, delete all references to the file from the filesystem). But the file descriptor is still valid. Any read and write calls will be successful, as they would with the filename still there.

In other words, you cannot fully delete a file until the file descriptor is closed. Once closed, the file will then be removed automatically.

With a valid file descriptor, you can check if the filename still exists, e.g.

printf("%d\n", buf.st_nlink);  // 0 means no filenames

Where buf is a struct stat initialised with fstat.

like image 94
teppic Avatar answered Oct 13 '22 00:10

teppic


Before writing to the file you could check if it is still there using access()

if (access("/yourfile",W_OK)!=-1) {
    //Write on the file
}

You can also do fstat on the descriptor:

struct stat statbuf;
fstat(fd,&statbuf);
if (statbuf.st_nlink > 0) {
    //File still exists
}

But it will slow your software down a lot, and also some program could link the file somewhere else and unlink the original name, so that the file would still be existing but under a different name/location, and this method would not detect that.

A much better alternative would be to use inotify on GNU/Linux, or kqueue on bsd, but I've never used the 2nd one.

You can use these API to watch changes in directories and get notifications from the kernel and get an event when your file is being deleted by some other process, and do something about it.

Keep in mind that this events are not in real time, so you could still use the file for a couple of milliseconds before getting the event.

like image 1
LtWorf Avatar answered Oct 13 '22 01:10

LtWorf