C++ get child process id from parent process id

4.7k views Asked by At

In windows 10, if i create a process to open calc.exe first its trigger calc.exe and exit that process after that it opens calculator.exe. How can i get actual process id that shows in task manager. i am using following code to create the process and display process id

if(!CreateProcess(("C:\\WINDOWS\\system32\\calc.exe"),
NULL,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&startup_info,
&pi) )
{
 args.GetReturnValue().Set(Nan::New(response).ToLocalChecked());
}
else
{

int dwPid = GetProcessId(pi.hProcess);
int v = dwPid->Int32Value();
args.GetReturnValue().Set(dwPid);
}
1

There are 1 answers

0
AudioBubble On
#include <iostream>
#include <vector>

#include <cstring>

#include <windows.h>
#include <tlhelp32.h>

using std::vector;
using std::cout;
using std::endl;

vector<DWORD> pids_from_ppid(DWORD ppid) {
  vector<DWORD> pids;
  HANDLE hp = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  PROCESSENTRY32 pe = { 0 };
  pe.dwSize = sizeof(PROCESSENTRY32);
  if (Process32First(hp, &pe)) {
    do {
      if (pe.th32ParentProcessID == ppid) {
        pids.push_back(pe.th32ProcessID);
      }
    } while (Process32Next(hp, &pe));
  }
  CloseHandle(hp);
  return pids;
}

int main(int argc,char *argv[]) {
  if (arc >= 2) {
    DWORD ppid = (DWORD)strtoul(argv[1], nullptr, 10);
    vector<DWORD> pidVec = pids_from_ppid(ppid);
    for (int i = 0; i < pidVec.size(); i++) {
      cout << pidVec[i] << endl;
    }
  }
  return 0;
}