I am writing a program that uses fork to create child processes and counts them when they are done. How can I be sure that I will not lose signals? What happens if a child sends a signal while the main program is still processing the previous signal? lost signal? how can i avoid this situation?
void my_prog() { for(i = 0; i<numberOfDirectChildrenGlobal; ++i) { pid = fork(); if(pid > 0)//parent //do parent thing else if(0 == pid) //child //do child thing else //exit with error } while(numberOfDirectChildrenGlobal > 0) { pause(); //waiting for signal as many times as number of direct children } kill(getppid(),SIGUSR1); exit(0); } void sigUsrHandler(int signum) { //re-register to SIGUSR1 signal(SIGUSR1, sigUsrHandler); //update number of children that finished --numberOfDirectChildrenGlobal; }
sigaction , , . , , , , ( , , ). .
, , , .
. , SIGCHLD , . waitpid WNOHANG , , .
waitpid
, SIGCHLD, , :
pid_t pid; while((pid = waitpid(-1, NULL, WNOHANG)) > 0) { nrOfChildrenHandled++; }
sigaction , .
To avoid this situation, you can use posix signals.