Use vfork() or posix_spawn().
Use vfork() or posix_spawn().
I could see it being worthwhile to immediately copy a few pages, like the top of the stack, but copying the whole resident set seems excessive. Especially since some of that data might not even be written to.
As well there's the cost of all those page faults that the two processes are likely to take to do the copying.
And lastly there's all sorts of complexity involving multiple parent threads calling fork(), or the child calling fork() again (or vfork()) before calling exec.
It's just much easier to copy the resident set and mark the address space as being CoW, because now you only have to worry about page faults for pages that are not in core anyways and so were going to fault anyways, and that means you don't have to worry about TLB shootdowns either (if a page is not in core, it's not referenced by any TLB either). You still have the multi-fork issues, but now you can use an atomic reference count on the address space.
With what you describe, you'd share nothing because at the point you've loaded it up, all the data you just loaded is resident. :-(
The posix_spawn() and posix_spawnp() functions provide the
functionality of a combined fork(2) and exec(3), with some
optional housekeeping steps in the child process before the
exec(3). These functions are not meant to replace the fork(2)
and execve(2) system calls. In fact, they provide only a subset
of the functionality that can be achieved by using the system
calls.
Also, there's no way to set resource limits in the child process, nor switch user or group ID, using posix_spawn().Windows defaults to CLOEXEC semantics and you have to opt-in to child process inheriting open file handles, and that has caused problems.
Unix defaults to not-CLOEXEC sematincs, and that too has caused problems.
The Unix default can cause unsolvable problems because of races between threads.
You should use CLOEXEC everywhere. Except you can't because you are using libraries.
A common hack I've had to add is an argument FD that is not to be closed because. e.g., an flock is held on it.