user3253461 user3253461 - 1 year ago 160
C Question

C/C++ program to kill all child processes of a parent process in UNIX?

I have a function which takes input parameter as PID.
e.g .

bool KillProcessTree (int ParentPID)


Now I want to write the definition of the above function, which will 1st get all the child processes and then kill them.

Is there any API in Unix which will take parent PID and will return the number of child processes created by the parent process?

Answer Source

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 kill(-pgid, signal_number).

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 setsid or setpgid, then kill the process group.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download