SIGCHLD handler not executing dependably
Hi, I'm trying to figure out how to use a SIGCHLD handler to execute reliably when a child worker process exits for use in larger projects, but this simple test isn't working. Since sigchld++ is executed every time the sig handler is called, and it fork()'s twice, I would expect it to print 2 every time, but it doesn't. Usually it's 2, but maybe 1/5 times it prints 1.
Code:
#include <iostream>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
int sigchld = 0;
void sigchld_handler(int signal){
sigchld++;
}
int main(){
signal(SIGCHLD, sigchld_handler);
if(fork() & fork()){
unsigned int leftover = 1;
while((leftover = sleep(leftover))); // The sleep is to allow both children time to exit.
cout << sigchld << endl;
}
return 0;
}