Search code examples
cparent-childkillzombie-processatexit

killing child processes at parent process exit


I'm very new to c and programming and need some help. In c on linux(cygwin) I am required to remove all child processes at exit. I have looked at the other similar questions but can't get it to work. I've tried-

atexit(killzombies); //in parent process

void killzombies(void)
{
    printf("works");
    kill(0, SIGTERM);
    printf("works");
    if (waitpid(-1, SIGCHLD, WNOHANG) < 0)
         printf("works");
}

for some reason, "works" doesn't even print ever. I press ctrl + c to exit.

ALSO I have tried-

prctl(PR_SET_PDEATHSIG, SIGHUP); //in child process
signal(SIGHUP, killMe);

void killMe()
{
    printf("works");
    exit(1);
}

but because I'm using cygwin, when I #include <sys/prctl.h>, cygwin says it can't find the file or directory and I don't know what package to install for it. Also, if my prctl() function were to work, would that kill all the zombies?

My program is a client server and my server forks() to handle each client. I'm suppose to leave no remaining zombies when the server shuts down.


Solution

  • From the Linux documentation of atexit(3):

    Functions registered using atexit() (and on_exit(3)) are not called if a process terminates abnormally because of the delivery of a signal.

    If you want to cleanup when your application receives a SIGINT or SIGTERM, you'll need to install the appropriate signal handlers and do your work there.