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?
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.
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.
I'd use brute force: for (i = 0; i < fd_max; ++i) close (i);
. Quick and pretty portable.
My solution for POSIX systems:
All opened fd's are the lowest value possible.
Make a wrapper function upon open(2)
.
Your new function open (and return) the requested fd and pass his value to a function called define_if_is_the_higtest_fd_and_store_it()
.
You should have a int hightest_fd_saved
accessible only for a singleton function (there is only 1 'descriptor table') named save_fd()
(initial value is 3 (cuz stderr
is 2)).
Configure SIGINT
to your signal function. Inside, you do a loop from [3, return_fd()
].
I think that's it...