Hi Tim, > i would like to ask for your expert knowledge. > > How to prevent file descriptor leaks in a multi-threaded application > that fork+exec. Quick answer is surely "use O_CLOEXEC" to close those > file descriptors on exec. > > But how does this work with fopen in a portable way ? > GNU libc has the 'e' flag for exactly this.
Yes [1]. > How about other non-GNU OSes / alternative C libraries ? POSIX [2][3], macOS [4], FreeBSD [5], Solaris [6] don't support this 'e' flag. How about using open() with O_CLOEXEC, and then fdopen()? Bruno [1] http://man7.org/linux/man-pages/man3/fopen.3.html [2] https://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html [3] http://man7.org/linux/man-pages/man3/fopen.3p.html [4] https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/fopen.3.html [5] https://www.freebsd.org/cgi/man.cgi?query=fopen&sektion=3&apropos=0&manpath=freebsd [6] https://docs.oracle.com/cd/E36784_01/html/E36874/fopen-3c.html