Kill a PID in C++

In this article, we are going to discuss how to kill a process using PID with a help of a C++ program.

Each process is uniquely identified using a process id or PID which is represented using positive numbers.

A process can have one or more child processes and each process has only one parent process. So if we kill a PID process then all its child processes will be killed. Here we consider two lists one is PID’s list and the other is PPID’s list(which means parent processes Pid).

For each process in the PID list, its parent process PID is represented at the corresponding index of a PPID’s list.

Example Program to kill a PID in C++ :

let’s consider an example, where we have lists PPID and PID, where PPIDs represent parent processes pid’s of corresponding index child processes in the PID list.

PPID = {4, 0, 4, 7, 3}

PID = {2, 4, 7, 3, 1}

kill pid = 7

The processes are like a tree structure. So, we have to store each parent process and its corresponding child processes in a map data structure.

In order to maintain the continuous chain of parent and child processes we will be using a queue data structure, so that we can keep track of all PIDs that will get killed when we kill the process with PID 7.  Finally, we will display a list of all killed process’s PIDs.

Code :

#include <bits/stdc++.h>
using namespace std;

int main(){
   int x,y,n;
   n = 5;
   vector<int> PPID = {4, 0, 4, 7, 3};
   vector<int> PID = {2, 4, 7 ,3, 1};
   int kill  = 7;
   //code to kill process with pid = 7
   map<int, vector<int>> c;
   vector<int> killed;
   for (int i = 0; i < n; i++) {
        x = PPID[i];
        y = PID[i];
    queue<int> q;
    while (!q.empty()) {
         int curr = q.front();
         for (int i = 0; i < c[curr].size(); i++) {
     //printing process pid's which have been killed
     cout<<"list of process pid's that are killed : ";
     for(int i = 0;i < killed.size(); i++)
         cout<<killed[i]<<" ";
     return 0;

Output :

list of process pid's that are killed : 7 3 1

In the above code, we have used some inbuilt functions of queue data structure. Like q.front() which is used to get the front element in the queue, q.pop() removes the front element from the queue, and q.push(Val) will insert the element at the end of the queue.

Hope you have understood the entire discussion.

Leave a Reply

Your email address will not be published. Required fields are marked *