How to check if a file with a file descriptor exists

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

+5
source share
2 answers

Unix-systems allow you to delete open files (or rather, delete all links to a file from the file system). But the file descriptor is still valid. Any read and write requests will succeed, as they will be with the file name.

In other words, you cannot completely delete a file until the file descriptor is closed. After closing, the file is automatically deleted.

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

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

Where bufis struct stat, initialized fstat.

+4
source

Before writing to a file, you can check if everything is there using access()

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

You can also execute fstat in the handle:

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

, - , , /, .

inotify GNU/Linux kqueue bsd, .

API , - , - .

, , , .

+1

All Articles