Prevent file descriptors inheritance during Linux fork

后端 未结 3 1845
死守一世寂寞
死守一世寂寞 2020-12-01 12:11

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

3条回答
  •  忘掉有多难
    2020-12-01 12:45

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

提交回复
热议问题