2 ms·
fork(2) is evil. I used to think fork(2)+exec(2) was genius and much more versatile than the WIN32 CreateProcess*() functions. The last part is still true, bu
by cryptonector 8y ago
fork(2) is evil.
I used to think fork(2)+exec(2) was genius and much more versatile than the WIN32 CreateProcess*() functions. The last part is still true, but I no longer think fork(2) is genius. fork(2) was genius back in the 70s when it was easier to do all the spawning work in user-land, but it's not actually a good thing, not now.
The only sane way to use fork(2) is to use it very early on in main() to start worker child processes. Or to immediately exit(2) or exec(2) on one or the other (or both) side(s) of fork(2) without calling any async-signal-UNsafe code on the child side. If you're going to exec() on the child side, then just use vfork(2) -- it's much easier and safer. Even better, if you're going to exec() on the child side then just use posix_spawn(3) and be done -- let the C library / OS figure out how best to spawn the child process. (On some systems posix_spawn() is a system call. On others it's implemented in terms of vfork(2) or clone(2) called in vfork(2)-like manner.)
The irony is that vfork(2) has the worse reputation, but it really is fork(2) that is evil. fork(2) is the root of much evil Unix-land:
- there are fork-safety considerations galore
- so you can only call async-signal-safe functions
on the child-side of the fork (unless you're
quite certain of the parent's state at the time
of the fork, which is why it's OK for the child
to continue if the fork was done early in main())
- it's EXPENSIVE
- copying the RSS, or all the writable data, or
arranging for CoW -- all of these are expensive
nowadays
- it complicates accounting of swap / VM space
(JNI code that calls fork(2) in a JVM with a 32GB
heap... really slows you down.)
- it has terrible semantics as to signals
- every time something is added to what it means to
be a process... one has to think about whether that
should be inherited across fork(2) or not
fork(2) is evil. Do not use. Especially do not expose fork(2) in other languages or their system libraries.