0

I'm running a C++ program under LINUX.
From my program's code I'm calling another program with a system() call:

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

But this calledProgram runs with multiple processes (with a specific names, say p1, p2, p3, p4).

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.
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.

Community
  • 1
  • 1
Heghine
  • 435
  • 3
  • 15
  • 1
    Check out this answer - http://stackoverflow.com/questions/392022/best-way-to-kill-all-child-processes. Perhaps, you can hook one of the solutions listed there to terminate signal handler of your program? – Ilya Kobelevskiy Jun 16 '15 at 13:37

2 Answers2

3

I recommend you to use fork/exec instead of system() to call your new program.That's easy.See this.

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. 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);  
}
Community
  • 1
  • 1
Ali Seyedi
  • 1,758
  • 1
  • 19
  • 24
1

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.

See: man 2 kill

mlom
  • 373
  • 3
  • 9
  • 1
    This is not true; killing a process _does not_ automatically kill all children. Usually if one sees behavior that looks like that's happening, it's caused by the children having a handle on a FIFO where their parent holds the other side; or the parent having a signal handler that shuts down its children on-exit; or similar. – Charles Duffy Jul 26 '21 at 22:40