Hey;
I am trying to handle the SIGCHLD and therefore prevent zombie processes walking around .)
The program does not work the way it should however. I am counting how many times the ZombieHandler is called and at the end of the program it says zero. What might be causing the error?
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <wait.h>
sig_atomic_t total = 0; // number of calls to ZombieHandler
void ZombieHandler(int signal_num) // wait for the child process and clean up
{
int status;
wait(&status);
total++;
}
int main(int argc, char** args)
{
struct sigaction sa;
memset(&sa, 0, sizeof sa);
sa.sa_handler = &ZombieHandler;
sigaction(SIGCHLD, &sa, NULL); // set sa as sigaction when SIGCHLD signal occurs
pid_t child;
child = fork();
if(child == 0) // child process
{
std::cout << "Child: My PID is " << getpid() << std::endl;
std::cout << "Child: My parent PID is " << getppid() << std::endl;
pid_t grandChild = fork();
if(grandChild == 0) // grand child process
{
std::cout << "GrandChild: My PID is " << getpid() << std::endl;
std::cout << "GrandChild: My Parent PID is " << getppid() << std::endl;
return 0;
}
else
{
return 0;
}
}
else // parent process
{
std::cout << "Parent: Number of calls to ZombieHandler is " << total << std::endl;
return 0;
}
}