Reputation:
I would like to know if there is a way to access a list of all open directories from the current process? I have a function that opens many directories recursively but exits the program as soon as something is wrong. Of course, I would like to close all directories before calling exit() without having to keep track of everything I open. Is this even possible?
Thanks!
Upvotes: 1
Views: 159
Reputation: 76949
When you exit()
, file handles are close()d
. This is good for one-time tools, but not good practice in the long run.
You should instead walk back up the recursion, close()ing
as you go. Replace, for example:
exit(1);
for:
close(current_fd);
return NULL;
Change your recursive call for:
if (thisfunc(...) == NULL) {
close(current_fd);
return NULL;
}
Upvotes: 0
Reputation: 91059
I have a function that opens many directories recursively but exits the program as soon as something is wrong. Of course, I would like to close all directories before calling exit() without having to keep track of everything I open.
I think your very approach is wrong. What is the point of opening the directories if you don't keep a handle on them?
You should keep a reference to the opened directory as long as you need it and discard it as soon as you can.
Keep in mind that normally, the nomber of open file descriptors is limited, e. g. to 1024.
Upvotes: 1
Reputation: 25129
You do not need to do this as exit()
will (eventually) exit the process, which will close all open file descriptors whether for directories or real files.
However, you absolutely do need to worry about valgrind
and friends reporting this, as this means fd
s are leaking in your program. But the solution is not to hunt around for open directories, but rather to simply ensure each opendir
is matched by a closedir
. That's what valgrind
is prompting you to do.
Upvotes: 0