So how do you implement fork() on a system that have a global memory model and thus don't actually have per-process memory mapping?Here's how you do it:1. Compile all object files as resident code (re-entrant code) with single section storing all static data (both sdata and sbss).2. First store values of local variables that the child process needs to static variables.3. Perform first part of the fork by spawning a new child process. Pause the parent and let the child process execute. Note that some sneaky setjmp/longjmp kind of magic has to be done the stack of the child process to proceed execution from the right point, as well as setting up the return value (pid) to 0 for the child. The return value indicates whether the execution is in the context of the child (0) or parent (the parent get's the pid of the newly created child process).4. In child: Allocate a new static data segment and copy the one from the parent. Note that since the parent is paused at this time it is safe to access the static data. Initialize the heap and other internal C library structures.5. In child: Copy the parent's state to the child. Anything that the child accesses that is stored in the local variables or heap must be cloned. This involves recreating all pointers, as the addresses will be different - just direct copying won't work. Note that since the parent is paused at this time it is safe to access the structures and heap and clone the necessary objects. Set local variables to point to either the new objects allocated or the values stored in the static variables at step 2.6. In child: Tell the parent process that it may continue execution.See? It's not that hard!But seriously, yes it's quite tricky. I have a hunch that hacks like this are kind of a lost art.#programming #hacking

you are viewing a single comment's thread
view the rest of the comments
[–] [S] 1 point 9 months ago

I've skipped a lot of detail in this simplified explanation, for example how to handle open file descriptors and similar icky bits. Hack like this also is far from true fork(), since the parent and the child definitely are quite different from each other in several ways.

  • source