Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C get all open file descriptors

I want to implement behavior in my C program so that if a SIGINT happens, I close all open file descriptors. Is there a simple way to get a list of them?

like image 982
user1190650 Avatar asked Oct 27 '12 15:10

user1190650


People also ask

What is an OpenFile descriptor?

File descriptor is integer that uniquely identifies an open file of the process. Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more!

What is file descriptor in C++?

With file descriptors we have some functions like open, close, read, write etc. to access files. A file descriptor is actually a integer number. Every opened file has it's own unique number. We call it a file descriptor. When we open a file with open () function it return a file descriptor.

How to use file descriptors to access files?

In C we can use two methods to access the file system. Those are file descriptors and file streams. In this document, we are going to see how we can use file descriptors to access files. With file descriptors, we have some functions like open, close, read, write, etc. to access files. A file descriptor is actually an integer number.

Should I close all open file descriptors?

@alk The OP states "close all open file descriptors", that includes those for the stdio streams. Show activity on this post. Keep track of all of your open file descriptors and close them individually. In the general case, a library you're using might have an open file, and closing it will cause that library to misbehave.


3 Answers

Keep track of all of your open file descriptors and close them individually.

In the general case, a library you're using might have an open file, and closing it will cause that library to misbehave.

In fact, the same problem could exist in your own code, because if you close file descriptors indiscriminately but another part of your program still remembers the file descriptor and tries to use it, it will get an unexpected error or (if other files have been opened since) operate on the wrong file. It is much better for the component responsible for opening a file to also be responsible for closing it.

like image 70
Kevin Reid Avatar answered Oct 17 '22 21:10

Kevin Reid


I'd use brute force: for (i = 0; i < fd_max; ++i) close (i);. Quick and pretty portable.

like image 4
Jens Avatar answered Oct 17 '22 21:10

Jens


You could read out the content of /proc/<pid>/fd., if available.

But be aware of the potiential race, that might occur if your application closes some or opens new ones in between your read out /proc/<pid>/fd and you are going to close what you read.

So conculding I want to recommend Kevin Reid's approach to this.

like image 4
alk Avatar answered Oct 17 '22 20:10

alk