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