▲ | alerighi a day ago | ||||||||||||||||
It's something trivial to write (~20 lines of code), there is no point for standard library to provide that kind of functions in my opinion. You do after the fork() (or clone, on Linux) a for loop that closes every FD except the one you want to keep. In Linux there is a close_range system call to close a range of in one call. POSIX is an API designed to be a small layer on the operating system, and designed to make as little assumption as possible to the underlying system. This is the reason why POSIX is nowadays implemented even on low resources embedded devices and similar stuff. At an higher level it's possible to use higher level abstractions to manipulate processed (e.g. a C++ library that does all of the above with a modern interface). | |||||||||||||||||
▲ | a day ago | parent | next [-] | ||||||||||||||||
[deleted] | |||||||||||||||||
▲ | deathanatos a day ago | parent | prev | next [-] | ||||||||||||||||
… what POSIX API gets you the open FDs? (Or even just the maximum open FD, and we'll just cause a bunch of errors closing non-existent FDs.) | |||||||||||||||||
| |||||||||||||||||
▲ | o11c a day ago | parent | prev [-] | ||||||||||||||||
It is always a bug to call `closerange` since you never know if a parent process has deliberately left a file descriptor open for some kind of tracing. If the parent does not want this, it must use `O_CLOEXEC`. Maybe if you clear the entire environment you'll be fine? That said, it is trivial to write a loop that takes a set of known old and new fd numbers (including e.g. swapping) produces a set of calls to `dup2` and `fcntl` to give them the new numbers, while correctly leaving all open fds open. |