29 points · by gbear605 · 8y ago · 13 comments
It’s crystal clear that you should not call fork() then execve() in any nontrivial process or multithreaded process. Use posix_spawn() or, if you must roll your own, use vfork() or clone(). Even if you can arrange to use fork() correctly like this, it’s very slow in a process that uses a lot of MAP_PRIVATE memory.
* https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/pos...
* https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/uni...
Under the hood in the musl C library, system() calls posix_spawn() which in turn calls clone().
* https://git.musl-libc.org/cgit/musl/tree/src/process/system....
* https://git.musl-libc.org/cgit/musl/tree/src/process/posix_s...
posix_spawn() is not a silver bullet either. Its API is cumbersome, it severly limits what you could do in the child process before exec(), and has no sane way to handle errors in the pre-exec() stage.
And AFACIS the glibc implementation of posix_spawn() doesn't even fix the memory duplication problem out of the box. It uses vfork() only if you use the non-standard POSIX_SPAWN_USEVFORK flag.
closefrom(2) is nice bsdism, btw. After setting up stdin, out and err, just closefrom(3). For the same money, it could have been designed to close a range instead, odd this was not selected.
Presumably for issues similar to those pointed out here.