C语言 杀死父进程的所有子进程但让父进程保持活动状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18433585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:15:46  来源:igfitidea点击:

Kill all child processes of a parent but leave the parent alive

cunixprocess

提问by Hypothetical inthe Clavicle

What would be the best way to kill all the processes of a parent but not the parent? Let's say I have an undetermined number of child processes that I've forked and on a given alarm, in my signal handler, I'd like to kill all my child processes but keep myself running for various reasons.

杀死父进程而不是父进程的最佳方法是什么?假设我有一个不确定数量的子进程,我已经分叉并在给定的警报中,在我的信号处理程序中,我想杀死我所有的子进程,但由于各种原因让自己继续运行。

As of now, I am using kill(-1*parentPid, SIGKILL) but this kills my parent along with its children.

截至目前,我正在使用 kill(-1*parentPid, SIGKILL) 但这会杀死我的父母及其孩子。

采纳答案by jxh

One way to accomplish this is to deliver some signal that can be caught (not SIGKILL). Then, install a signal handler that detects if the current process is the parent process or not, and calls _exit()if it is not the parent process.

实现这一点的一种方法是传递一些可以被捕获(而不是SIGKILL)的信号。然后,安装一个信号处理程序来检测当前进程是否是父进程,_exit()如果不是父进程则调用。

You could use SIGUSR1or SIGUSR2, or perhaps SIGQUIT.

您可以使用SIGUSR1SIGUSR2,或者也许SIGQUIT

I've illustrated this technique here.

我已经在这里说明了这种技术。

Optionally (as suggested by Lidong), the parent process can use SIG_IGNon the signal before issuing the kill()command.

可选(根据 Lidong 的建议),父进程可以SIG_IGN在发出kill()命令之前在信号上使用。

signal(SIGQUIT, SIG_IGN);
kill(-parent_pid, SIGQUIT);

回答by Lidong Guo

Jxh 's answer is nice. Howevr , maybe you can just give a signal handerfor every children process after forkand let it call exitfunction . and you give a signal handerfor parent and let it ignorethe signal (like SIGUSR1). this may add the code lines but you don't need detect the process is parent or child in signal hander function.

Jxh 的回答很好。但是,也许您可​​以signal hander为每个子进程提供一个afterfork并让它调用exitfunction 。然后你给signal hander父母一个,让它ignore发出信号(比如SIGUSR1)。这可能会添加代码行,但您不需要在信号处理函数中检测进程是父进程还是子进程。

回答by f_x_p

you can set the child process a new process group at the fork time, and while you want to kill the child process and its descendants, you can use killpg, example code as:

您可以在 fork 时为子进程设置一个新的进程组,当您想杀死子进程及其后代时,您可以使用killpg,示例代码为:

#include <unistd.h>
#include <signal.h>
#include <stdio.h>

void parent(pid_t pid) {
    killpg(pid, SIGKILL);
}

void child(void) {
    if (-1 == setsid())
        return;

    while(1) {
        sleep(1);
        printf("child\n");
    } 
}


int main() {
    pid_t pid;
    switch ((pid=fork())) {
    case 0: // child
        child();
        break;

    default: // parent
        getchar();
        getchar();
        parent(pid);
    }

    return 0;
}