I have a function which takes input parameter as PID.
bool KillProcessTree (int ParentPID)
There is no standard Unix API to retrieve the list of child processes of a given process.
You can list all the processes on the system with their parent process, and build the process tree from that. The portable way to do this is to run the command
ps -e -o ppid= -o pid=
and parse the output (
popen followed by a loop of
scanf("%ld %ld\n") will do). Store the data as a finite map from PPID to PID, then walk the tree to collect the list of descendants of the process you're interested in.
If any of the processes concerned forks or exits during your processing, you may miss it. If you're unlucky, a process may exit and its PID may get reused while you're doing all this. Also, if process P forks a child process Q which forks a grandchild R, and then Q exits, R's PPID will be set to 1, so you won't detect that R was originally a descendant of P.
In a nutshell: whatever your problem is, this is very probably the wrong approach.
Unix has a feature to deal with this: process groups. There's a good chance that process groups are the answer to the problem you're trying to solve. You can atomically send signal
signal_number to all the processes in a process group with
You should arrange for all the processes you want to kill to belong to the same process group, and for the processes you don't want to kill not to belong to that process group. Make the parent process call
setpgid, then kill the process group.