Comment by jsmith45

4 years ago

Sure but if you have code like the following:

    pid = vfork();
    if (pid==0) {
       int something;
       exec();
       // cleanup code that uses something
       _exit(1);
    }

Then the compiler (which knows `_exit` is noreturn) can conclude that if you enter the `if`, none of the existing stack slots will be read again, so it can reuse one of those stack slots for the `something` variable. But whoops, that means the original process has has its stack corrupted.

This applies even when the variable declared at start of method, as compilers can perform equivalent variable lifetime analysis to let it reuse the stack slot. This is exactly why the POSIX spec makes it undefined to write to any variable after vfork (except the pid return variable, obviously).

But even that is not strictly safe enough, since the compiler is allowed to introduce writes to the stack. This may for example, happen as part of calculating a temporary, if the compiler wants to use the register for something else, and decides against using some other register for storage, so spills to the stack.

Obviously your `afork` completely avoids all those sorts of concerns by using a separate stack.