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.
When you're done with a file, use close() to close it and free up the resources that were tied with the file and is done using Python close() method.
The close() method closes an open file. You should always close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With