Understanding SIGCHLD at the end of a child process

I can not understand the output for the next program. I noticed that after the child process returns, the parent process will not sleep for 3 seconds before waiting (). If SIGCHLD is set to the default handler, then it sleeps for 3 seconds, causing a wait and return, as expected. What's going on here?

# include <unistd.h> # include <sys/types.h> # include <stdio.h> # include <sys/wait.h> # include <signal.h> void handler(int sig) { printf("Iam in handler ...\n"); } main() { int status; pid_t pid; struct sigaction act; //act.sa_flags=SA_NOCLDSTOP; act.sa_handler=handler; sigaction(SIGCHLD,&act,NULL); if(!fork()) { printf("child process id is %d\n",getpid()); return 1; } printf("xxx ...\n"); sleep(3); pid = wait(&status); printf("process terminated is %d\n",pid); } output:: xxx ... child process id is 2445 Iam in handler ... process terminated is 2445 
+6
source share
2 answers

When the child process dies, a SIGCHLD sent to the parent. In your case, it interrupts sleep , and it looks like the process is not sleeping.

The essence of the problem: sleep does not restart when the signal is interrupted.

+8
source

From person to sleep () :

sleep () causes the calling thread to fail before the seconds elapse, or a signal arrives that is not ignored.

Your child finishes, triggers a signal to wake you up.

Return value sleep() :

Zero value, if the requested time has elapsed, the number of seconds remaining before sleep, if the call was interrupted by the signal handler.

It can be used if you want to help you “finish” the dream.

 unsigned sleep_time = 3; ... while((sleep_time = sleep(sleep_time)) > 0) {} pid = wait(&status); ... 
+11
source

All Articles