I don't know what the proper way to do this portably, but this is the diff we currently have in NetBSD's xsrc for xsm to close file descriptors on exec. I see that glibc added fopen's "e" flag for 2.7 (in 2007). No idea about other operating systems, the flag was new to me too :)