Is it possible to mark a specific file descriptor as not inheritable, or close it, in the child process when fork()
is invoked?
Asked
Active
Viewed 1,366 times
4

zer0stimulus
- 22,306
- 30
- 110
- 141
-
4Possible duplicate of [Prevent file descriptors inheritance during Linux fork](https://stackoverflow.com/q/5713242/608639) – jww Apr 18 '19 at 18:06
3 Answers
10
No. All file descriptors are inherited in fork. You can set a fd to be closed on exec, however, by using fcntl(fd, F_SETFD, FD_CLOEXEC)
.

bdonlan
- 224,562
- 31
- 268
- 324
-
3Also note that you can save the `fcntl` by passing `O_CLOEXEC` to `open` under Linux. – Damon Jul 06 '11 at 17:04
-
1@Damon: Or any POSIX 2008 conformant system (`O_CLOEXEC` was standardized with POSIX 2008). – R.. GitHub STOP HELPING ICE Aug 29 '11 at 14:52
0
No its not possible. By default child processes with inherit file table from parent process.

CrazyCoder
- 2,465
- 8
- 36
- 57
0
If you really want close-on-fork, something like this could work:
static void fd_to_close;
static void closer()
{
close(fd_to_close);
}
pthread_atfork(0, 0, closer);
Normally close-on-exec is the desired behavior anyway, though.

R.. GitHub STOP HELPING ICE
- 208,859
- 35
- 376
- 711