Skip to content

Instantly share code, notes, and snippets.

@AlmuHS
Last active March 22, 2023 13:03
Show Gist options
  • Save AlmuHS/577739fc90f9039597706ccbb397d132 to your computer and use it in GitHub Desktop.
Save AlmuHS/577739fc90f9039597706ccbb397d132 to your computer and use it in GitHub Desktop.
Get the child of a process by its name in Linux
#include <algorithm>
#include <vector>
#include <iostream>
#include <fstream>
#include <proc/readproc.h>
void ProcIdFromParentProcId(int parentProcId, std::vector<int>& procId) {
PROCTAB *proc = openproc(PROC_FILLSTAT);
while (proc_t *proc_info = readproc(proc, nullptr)) {
if (proc_info->ppid == parentProcId) {
procId.push_back(proc_info->tgid);// i++;
}
freeproc(proc_info);
}
}
pid_t get_pid_by_name(std::string name){
char buf[512];
std::string command = "pidof -s " + name;
FILE *cmd_pipe = popen(command.c_str(), "r");
fgets(buf, 512, cmd_pipe);
pid_t pid = strtoul(buf, NULL, 10);
pclose( cmd_pipe );
return pid;
}
std::string get_name_by_pid(pid_t pid){
char file_path[100];
sprintf(file_path, "/proc/%d/task/%d/comm", pid, pid);
std::ifstream file(file_path);
std::string proc_name;
std::getline(file, proc_name);
return proc_name;
}
int main(){
std::vector<int> procs;
std::string process_name;
std::cout<<"Enter the process name: ";
std::cin>>process_name;
//Get PID by name
int pid_process = get_pid_by_name(process_name);
std::cout<<"The PID of this process is: "<<pid_process<<"\n";
//Get child process by PID
ProcIdFromParentProcId(pid_process, procs);
std::cout<<"The child process are: ";
for(int i = 0; i < procs.size(); i++){
pid_t pid = procs[i];
std::string proc_name = get_name_by_pid(pid);
std::cout<<pid<<"("<<proc_name<<")\n";
}
std::cout<<std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment