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

标签 c linux multiprocessing kill

在我调用的主要父进程中:

killpg(child_group, SIGKILL);

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

setsid();
child_group = getpgrp();

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

最佳答案

在父进程中:

killpg(child_group, SIGKILL);

您实际上是如何获得child_group的?

为此目的在子进程中执行以下操作是没有意义的:

child_group = getpgrp();

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


SIGKILL 必须发送到与子进程 PID 相对应的 PGID,因为它通过 setsid()。也就是说,作为 killpg() 的参数,您应该使用通过调用 fork() 返回到父进程的 pid_t

确保 killpg() 被父级调用 after setsid() 在子级中(成功)返回(即:之后 child 已经成为流程组领导,而不是之前)。


一个最小的例子:

#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;
}

关于c - 为什么我不能用这个c代码杀死进程组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48561419/

相关文章:

C从txt文件中提取除空格和标点符号之外的单词

c - 使用 readv() linux 系统调用时,冗余字符被添加到缓冲区之一

c - 想在 C 中创建一个写模式的文件

c - 如何在 linux 内核中以编程方式读取 linux 文件权限

python - 多处理导致错误的无限循环

c - 格式字符串未使用数据参数 - 输出长整型

c - 在 C 中与 atoi() 一起使用

linux - 参数类型 : "const char __user *const __user *argv" 的含义是什么

multithreading - Lua 是一种基于事件的编程语言吗?

python - 多处理提前退出