Reputation: 8505
I have file descriptor and inside my signal handler, i close the file. But due to other conditions, the file could have been closed earlier. Is there a way to check if the file descriptor points to an open file in c and linux?
UPDATE: Is it possible to determine filename associated with a file descriptor? This way if the fd gets recycled, app can detect it.
Upvotes: 6
Views: 9905
Reputation: 70921
After you closed the file descriptor fd
assign -1
to it, so you later could test fd
against -1
to see if you already closed it.
You could lookup the filename a (valid) file descriptor referrs to by calling readlink()
on /proc/<pid>/fd/<file descriptor>
.
Upvotes: 2
Reputation: 13414
Try to do any file operation like lseek
on the file descriptor. If it returns -1
. Then check errno
, if its EBADF
then the file descriptor is already closed.
Try to do lseek
in an unaffected manner like below.
lseek(fd, 0, SEEK_CUR);
Usually while opening the first file in a program we always get the file descriptor as 3
. After this file is closed, if we try to open some other file we will get the same file descriptor as 3
. Because always we will get the lowest available number. If we are closing and reopening many files in a program, then we need to improve our code to track of file descriptors list to check whether its closed or not.
Upvotes: 5
Reputation: 1866
When you open a file, it always get the minimal available fd assigned. So if you close your fd, and then open another file somewhere in your code, you could easily have the same fd reassigned to this new file. So there is no reliable way to tell that the file descriptor is closed, because it can now point to another opened file.
Upvotes: 2