How do you prevent a file descriptor from being copy-inherited across fork()
system calls (without closing it, of course)?
I am looking for a way to mar
There's no standard way of doing this to my knowledge.
If you're looking to implement it properly, probably the best way to do it would be to add a system call to mark the file descriptor as close-on-fork, and to intercept the sys_fork
system call (syscall number 2) to act on those flags after calling the original sys_fork
.
If you don't want to add a new system call, you might be able to get away with intercepting sys_ioctl
(syscall number 54) and just adding a new command to it for marking a file description close-on-fork.
Of course, if you can control what your application is doing, then it might be better to maintain user-level tables of all file descriptors you want closed on fork and call your own myfork
instead. This would fork, then go through the user-level table closing those file descriptors so marked.
You wouldn't have to fiddle around in the Linux kernel then, a solution that's probably only necessary if you don't have control over the fork process (say, if a third party library is doing the fork()
calls).
No. Close them yourself, since you know which ones need to be closed.
If you fork
with the purpose of calling an exec
function, you can use fcntl
with FD_CLOEXEC
to have the file descriptor closed once you exec
:
int fd = open(...);
fcntl(fd, F_SETFD, FD_CLOEXEC);
Such a file descriptor will survive a fork
but not functions of the exec
family.