简体   繁体   English

当父母被杀死时,杀死所有子进程

[英]Kill all the child processes when parent is killed

I'm running a C++ program under LINUX. 我正在LINUX下运行一个C ++程序。
From my program's code I'm calling another program with a system() call: 从程序的代码中,我正在使用system()调用来调用另一个程序:

system("calledProgram opt1 opt2 ... opt_n");

But this calledProgram runs with multiple processes (with a specific names, say p1 , p2 , p3 , p4 ). 但是,这个被calledProgram运行有多个进程(具有特定名称,例如p1p2p3p4 )。

How can find and kill these processes when my program is being killed externally by the user. 当我的程序被用户外部杀死时,如何找到并杀死这些进程。

Here ( How to kill process in c++, knowing only part of its name ) described how to find processes with a specific name and kill them. 这里( 如何杀死c ++中的进程,只知道其名称的一部分 )描述了如何查找具有特定名称的进程并杀死它们。
But what if user runs the program with the same options from different directories. 但是,如果用户使用来自不同目录的相同选项运行程序,该怎么办? Should I check for the running directory also to find correct processes? 我是否还应该检查运行目录以找到正确的进程?

Is there another (better) way to kill those child processes? 还有另一种(更好的)方式杀死那些子进程吗?

PS: When I'm running calledProgram from the cmd line, and then, killing it by ctrl+c, its processes are not being killed automatically. PS:当我从cmd行运行calledProgram的程序时,然后通过ctrl + c将其杀死,它的进程不会自动被杀死。

I recommend you to use fork/exec instead of system() to call your new program.That's easy.See this . 我建议你使用fork / EXEC而不是system()调用新的program.That的easy.See

It seems necessary for your application since you need "calledProgram" to be child of your program so it'll die when someone kills your program. 您的应用程序似乎很有必要,因为您需要“被调用的程序”作为程序的子级,这样当有人杀死您的程序时,它就会死掉。

You also need to handle SIGINT signal. 您还需要处理SIGINT信号。 In the most simple way you need something like this: 用最简单的方法,您需要这样的东西:

#include<signal.h>

void signal_handler() 
{
    kill(0,SIGTERM);
}

int main() 
{    
    signal(SIGINT,signal_handler);  
}

When killing a process all child processes are killed. 当杀死一个进程时,所有子进程都被杀死。 This is true for child processes that has not detached. 对于尚未分离的子进程,这是正确的。

Your process only has to remember the pids of it's nearest children and kill them. 您的过程只需要记住附近的孩子的小知识并杀死他们即可。 The childrens child processes will automatically die. 孩子的孩子进程将自动死亡。

If you put all child processes in the same process group, you can kill all with a single kill(2) call. 如果将所有子进程放在同一进程组中,则可以通过单个kill(2)调用来杀死所有子进程。

See: man 2 kill 参见:男子2杀

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

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