tags:

views:

147

answers:

2

How do I find all the open files in a process (from inside itself)?

This seems useful to know after a fork() (before exec()).

I know of the existance of getdtablesize() and the more portable sysconf(_SC_OPEN_MAX), but it seems inefficient to attempt closing every valid file descriptor, whether there's an open file behind it or not. (I am also aware of the dangers of premature optimisation, this is more about aesthetics I guess :-)

+2  A: 

It may sound inefficient to attempt to close all file descriptors, but it actually is not that bad. The system call implementation to lookup a file descriptor should be fairly efficient if the system is any good.

If you want to find only close the open file descriptors, you can use the proc filesystem on systems where it exists. E.g. on Linux, /proc/self/fd will list all open file descriptors. Iterate over that directory, and close everything >2, excluding the file descriptor that denotes the directory you are iterating over.

Martin v. Löwis
+1  A: 

The existing mechanisms are platform specific. See this answer:
http://stackoverflow.com/questions/899038/getting-the-highest-allocated-file-descriptor/918469#918469

mark4o