What does the FD_CLOEXEC fcntl () flag do?

Same:

if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) { ... 

Although I read man fcntl , I can't figure out what it does.

+62
c
May 25 '11 at 13:18
source share
3 answers

It sets the close-on-exec flag for the file descriptor, which causes the file descriptor to automatically (and atomically) close when any of the exec family functions succeeds.

It also checks the return value to see if the operation was unsuccessful, which is useless if the file descriptor is valid, since there is no condition under which this operation should fail with a valid file descriptor.

+57
May 25, '11 at 13:21
source share

It marks the file descriptor, so it will close() d automatically when the process or any of its children fork() calls one of the exec*() function families. This is useful for preventing file descriptors from leaking into random programs executed by, for example, system() .

+23
May 25 '11 at 13:21
source share

This will allow the OS to automatically close the file descriptor if any other process executes the file you open (your fd refers to the file). This is more useful when writing scripts and multi-threaded software environments.

-7
Nov 25 '14 at 18:12
source share



All Articles