문제

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!

도움이 되었습니까?

해결책

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.

다른 팁

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 fds 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.

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top