简体   繁体   中英

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

I have a function which takes input parameter as PID. eg .

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?

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.

I would simply store all the child pids when fork(), in an array of pid_t in the parent process.

after then, kill all by looping that array.

pid_t all_child[10]; // you should not define a fixed length array, you can use pointer.
if((pid = fork()) == 0)
{
     //child processes
}
else
{
//parent process
all_pid[counter] = pid;
}

When killing,

for( i = 0; i < counter; i++)
{
kill(all_pid[i], SIGTERM);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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