简体   繁体   English

杀死bash和子进程

[英]Kill bash and child process

My C program executes commands in a bash shell. 我的C程序在bash shell中执行命令。 To do this, I fork and in the child process I run: 为此,我fork并在子进程中运行:

char* command = "..."; /* provided by user */
execlp("/bin/bash", "bash", "-c", command, NULL);

If this is a long running command, I would like to have the option of killing it. 如果这是一个长期运行的命令,我想选择杀死它。 For example, say I'm doing: 例如,说我在做:

execlp("/bin/bash", "bash", "-c", "find / test", NULL);

After this, I know the PID of the child that is executing bash, but bash is forking a separate process to execute find. 此后,我知道正在执行bash的孩子的PID,但是bash正在分叉一个单独的进程来执行find。

$ ps aux | grep find
zmb       7802  0.0  0.1   5252  1104 pts/1    S+   11:17   0:00 bash -c find / test
zmb       7803  0.0  0.0   4656   728 pts/1    S+   11:17   0:00 find / test

I can kill the bash process (7802), but the find process (7803) still continues to execute. 我可以杀死bash进程(7802),但是find进程(7803)仍然继续执行。 How can I ensure that the bash process propagates signals to it's children? 我如何确保bash进程将信号传播到其子进程?

It will send a SIGTERM to the Process Group ID passed in parameter and to all children. 它将SIGTERM发送到传入参数的进程组ID以及所有子级。

kill -- -$(ps -o pgid= $PID | grep -o [0-9]*)

Also, more answers on this post : Best way to kill all child processes 另外,有关此帖子的更多答案: 杀死所有子进程的最佳方法

from man 2 kill : man 2 kill

If pid is less than -1, then sig is sent to every process in the process group whose ID is -pid. 如果pid小于-1,则将sig发送到ID为-pid的进程组中的每个进程。

That is you may kill all children, direct or indirect which weren't created its own process group. 也就是说,您可能会杀死所有未创建自己的进程组的直接或间接子级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM