Closing all open files in a process

Magnus picture Magnus · Aug 22, 2009 · Viewed 20.4k times · Source

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 :-)

Answer

R.. GitHub STOP HELPING ICE picture R.. GitHub STOP HELPING ICE · Jun 29, 2011

If your program will be calling fork and exec, you really should open all file descriptors with the O_CLOEXEC flag so you don't have to manually close them before exec. You can also use fcntl to add this flag after a file is opened, but that's subject to race conditions in multithreaded programs.