What does the FD_CLOEXEC fcntl() flag do?

C

C Problem Overview


Like so:

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

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

C Solutions


Solution 1 - C

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.

Solution 2 - C

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().

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioncompile-fanView Question on Stackoverflow
Solution 1 - CR.. GitHub STOP HELPING ICEView Answer on Stackoverflow
Solution 2 - CgeekosaurView Answer on Stackoverflow