Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if the file is closed

Tags:

c

linux

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.

like image 618
Jimm Avatar asked Jan 15 '13 17:01

Jimm


People also ask

How do I make sure a file is closed in Python?

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.

What does file close () do?

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.


1 Answers

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.

like image 193
rashok Avatar answered Nov 02 '22 13:11

rashok