What I'm trying to do is have a child process run in the background while the parent goes and does something else. When the child returns, I'd like for the parent to get that status and do something with it. However, I don't want to explicitly wait for the child at any point.
I looked into the WNOHANG option of waitpid but this seems to be a little different than what I'm looking for. WNOHANG just only gets the status if it's done, otherwise it moves on. Ideally, I'd like some option that will not wait for the process, but will jump back and grab the return status when it's done.
Is there any way to do this?
Code example:
pid_t p = fork();
if (p == 0){
value = do_child_stuff();
return(value);
}
if (p > 0){
captureStatus(p, &status); //NOT A REAL FUNCTION
// captureStatus will put p's exit status in status
// whenever p returns, without waiting or pausing for p
//do other stuff.....
}
Is there any way to simulate the behavior of captureStatus?
You could establish a signal handler for SIGCHLD
and wait
for the process once that triggers (it will trigger when the child terminates or is killed).
However, be aware that very few useful things can be done in a signal handler. Everything must be async-signal-safe. The standard specifically mentions wait
and waitpid
as safe.