What does the FD_CLOEXEC fcntl() flag do?
Li开发者_C百科ke 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.
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()
.
Note that the use of this flag is essential in some multithreaded programs, because using a separate fcntl(2) F_SETFD
operation to set the FD_CLOEXEC
flag does not suffice to avoid race conditions where one thread opens a file descriptor and attempts to set its close-on-exec flag using fcntl(2)
at the same time as another thread does a fork(2)
plus execve(2)
. Depending on the order of execution, the race may lead to the file descriptor returned by open()
being unintentionally leaked to the program executed by the child process created by fork(2)
.
(This kind of race is, in principle, possible for any system call that creates a file descriptor whose close-on-exec flag should be set, and various other Linux system calls provide an equivalent of the O_CLOEXEC
flag to deal with this problem.)
精彩评论