Like so:
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
...
Though I've read man fcntl
, I can't figure out what it does.
It sets the close-on-exec flag for the file descriptor, which causes the file descriptor to be automatically (and atomically) closed when any of the exec
-family functions succeed.
It also tests the return value to see if the operation failed, which is rather useless if the file descriptor is valid, since there is no condition under which this operation should fail on a valid file descriptor.
FILE *
) associated with the file descriptor. One valid use for FD_CLOEXEC is to close a log file that the parent process has open when executing a shell process. Note that POSIX 2008 has an option to open(2)
for O_CLOEXEC - so you can set this property when you open the file, which will be very useful once it is widely available.
May 25, 2011 at 14:11
open
and not accept
, socket
, pipe
, etc...
May 25, 2011 at 14:19
dup()
and dup2()
are not affected, of course). You'd probably have to have new functions with an extra 'mode' or 'flags' parameter, which is presumably why it didn't happen. If you could use O_CLOEXEC on socket, then you could suppose that accept()
would clone that flag on the descriptor it returns. But socket()
and pipe()
are trickier.
May 25, 2011 at 14:27
dup
and dup2
are affected. The close-on-exec flag applies to file descriptors, not open file descriptions, so it's not shared across duplicated file descriptors. That is a very good thing.
May 25, 2011 at 14:33
dup3
, pipe2
, and accept4
. Also, socket
has the SOCK_CLOEXEC
flag you can combine with the requested socket type.
Mar 10, 2014 at 16:30
It marks the file descriptor so that it will be close()
d automatically when the process or any children it fork()
s calls one of the exec*()
family of functions. This is useful to keep from leaking your file descriptors to random programs run by e.g. system()
.