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,067 times
4
zer0stimulus
- 20,576
- 30
- 105
- 139
-
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
- 214,833
- 29
- 259
- 321
-
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,305
- 8
- 32
- 51
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
- 201,833
- 32
- 354
- 689