Ina console application, passing _P_OVERLAY
to a spawn
function (which has the same effect as calling exec
), destroys the current process.
This would be the desired behavior if it were not for the fact that doing so causes the calling process (which is often cmd.exe
) to assume its callee has returned, whereas in reality the spawned sub-process of that callee is still running and therefore the caller should wait for that callee to terminate before continuing to use the console.
So, if the caller is cmd.exe
(the command prompt), what happens is that as soon as the callee spawns the sub-process, the user is immediately prompted with the C:\Users\User>
prompt, and becomes free to type in more commands, even though the sub-process is still running.
The best solution I have is to avoid terminating the current process until the child has terminated, but I'm wondering: is there any way to have the calling process wait on the spawned sub-processes before continuing when the callee has terminated?
No, there is no way to do this - if you want cmd.exe
to wait for your child to exit, then you need to wait for your child to exit.
The reason is that when cmd.exe
launches your process it receives a process handle; it then waits for that process handle to become signaled. Most other parents (for example, the C runtime library) will behave the same way. Process handles are signaled when the process they refer to exits, and there is no way to change that behaviour.
Workaround: presumably you are using _P_OVERLAY because you're porting from UNIX code. If there is too much code to conveniently change all of the instances to wait for the child before exiting, you could start a child process as soon as your process starts, and run all of the UNIX-based code in the child. In this model, the only thing the top-level process does is to wait for the rest of the process tree to exit. (You can use a job object to keep track of the process tree.)