在我调用的主要父进程中:
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/