Tuesday, June 27, 2006

SIGCHLD

While I was trying to write a Process Monitoring "Process" for my current employer ( well actually it is Process Monitoring Daemon ) I was breaking my head for almost 1 hour before figuring out what is really going on. I knew SIGCHLD is ignored by default. But I was under impression since I block the signal and wait on that signal specifically I should get the signal. Well it turns out that I won't. You won't either...! You need to specifically install a signal handler before sigwaiting on SIGCHLD. If you remove the sigaction from the below program the while(1) loop will never get to see the SIGCHLD when a child terminates.


#include
#include
#include

static void handle_signal(int signum)
{
printf("got signal %d", signum);
}


main()
{
sigset_t sig_set;
struct sigaction sa;
int signum;
int status;
int pid;
pthread_t tsig;


sa.sa_handler=handle_signal;
sa.sa_flags=0;
sigemptyset(&sa.sa_mask);
sigaction(SIGCHLD, &sa, NULL);

pthread_sigmask(SIG_BLOCK, &sig_set, NULL);

pid = fork();
if ( pid == 0 ) {
if (execve( "test.sh",
NULL,NULL ) < 0) {
perror("execve");
}
} else {
while (1) {
sigwait(&sig_set,&signum);
if ( signum == SIGCHLD ) {
int pid = wait(&status);
}
}
}
}

No comments: