为什么我不能用这个 C 代码杀死进程组?

why I cannot kill the process group with this c code?

在主父进程中我调用了:

killpg(child_group, SIGKILL);

在子进程中,我将子组设置为:

setsid();
child_group = getpgrp();

但是我检查了进程,ps显示进程组没有被杀死。 我做错了什么?

在父进程中:

killpg(child_group, SIGKILL);

你是怎么得到child_group的?

为此在子进程中执行以下操作毫无意义:

child_group = getpgrp();

那是因为这个child_group只是子进程中的一个副本(即:父进程中的child_group没有被修改)


SIGKILL必须发送到对应子进程PIDPGID,因为它成为一个进程组通过 setsid() 领导。也就是说,作为 killpg() 的参数,您应该使用通过调用 fork().

返回给父进程的 pid_t

确保 killpg() 被父级调用 setsid() 被(成功地)返回到子级中(即:在子级成为进程组长而不是之前)。


一个最小的例子:

#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
        // wait some time to let setsid() complete
        sleep(5);
        parent(pid);
    }

    return 0;
}