I have learned that a signal can occur at any location when running one's code. For example, this code:
pid_t child;
void cleanup(int signal) {
int status;
while (waitpid((pid_t) (-1), 0, WNOHANG) > 0) {}
}
int main() {
// Register signal handler BEFORE the child can finish
signal(SIGCHLD, cleanup); // or better - sigaction
child = fork();
if (child == -1) { exit(EXIT_FAILURE);}
if (child == 0) { /* I am the child!*/
// Do background stuff e.g. call exec
} else { /* I'm the parent! */
sleep(4); // so we can see the cleanup
puts("Parent is done");
}
return 0;
}
I have also learned that you cannot do much inside a signal function handler besides affecting a sig_atomic_t variable. Is that true for waiting for a child-process as well? If so, what is the best way to handle a SIGCHLD
?