killing child processes at parent process exit

情到浓时终转凉″ 提交于 2019-12-06 10:41:33

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.

Your waitpid does not supply the usual parameters, I'm surprised it does not crash. The prototype is:

pid_t waitpid(pid_t pid, int *status, int options); 

The second parameter should be a pointer to an int, you are supplying an int. Notice also that you should call waitpid for each child, you are only calling it for one.

atexit() is only called if you exit normally. If you are exiting through CTRL+C then you need to call your function from a handler on SIGINT.

You'll need to keep track of how many children your process has and then call wait that many times. Also, as others have said, your atexit() function won't be called if the process is terminated by a signal, so you'll need to call killzombies() from a signal handler as well. You'll need something like:

int n_children = 0; // global

void handle_sig(int sig) {
    killzombies();
    exit(sig);
}

// your atexit()
void killzombies() {
    kill(0, SIGKILL);
    while (n_children > 0) {
        if (wait(NULL) != -1) {
            n_children--;
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!