简体   繁体   中英

How to enumerate file descriptors? (to close them after fork)

I have a large program. It very likes to open files (works with them, amount can be giant - more then 10k ). At some point I want to born a subprocess which will live its own life ( out-of-proc web browser ). I don't control who and how creates files in my main program by reason of its size ( > 10GB of code ) and third-party (plug-ins as well) dependencies. I'd want either:

  • O_CLOEXEC / FD_CLOEXEC by default. I suspect there is no such ability. Or
  • a way to enumerate all file (socket,pipe so on) descriptors in order to be able to close them after fork. Operation systems of interest: Mac OS X and Linux.

File descriptors are all small positive integers, so you can enumerate all of them and close them. Closing one that isn't open will cause an error, but you can ignore that:

#include <sys/resource.h>
struct rlimit lim;
getrlimit(RLIMIT_NOFILE, &lim);
for (int i = 3; i < lim.rlim_cur; i++)
    close(i);   // close all file descriptors other that stdin/stdout/stderr

Setting close-on-exec by default is not possible.(Related: how to set close-on-exec by default ).

Enumerating all file descriptors within a process, you can look up /proc/PID/fd/ in Linux. In Mac OS X however, I don't have any programatic solution except using lsof(8) utility. lsof(8) is also available on Linux.

EDIT: Or, you can override open(2) call to specify O_CLOSEXEC by default and run your program using LD_PRELOAD on Linux. For Mac, follow What is the exact equivalent to LD_PRELOAD on OSX? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM