C ++从父进程id获取子进程ID

时间:2017-01-09 08:49:34

标签: c++ visual-c++ windows-10 createprocess

在Windows 10中,如果我创建一个进程来打开calc.exe,首先触发calc.exe并退出该进程,然后打开calculator.exe。如何获得任务管理器中显示的实际进程ID。 我正在使用以下代码来创建流程并显示流程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 个答案:

答案 0 :(得分:0)

#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
#include <cstring>
#include <sstream>
#include <string>
#include <vector>

using std::string;
using std::to_string;
using std::vector;
using std::cout;
using std::endl;

vector<string> string_split(string str, char delimiter) {
  vector<string> vec;
  std::stringstream sstr(str);
  string tmp;
  while (std::getline(sstr, tmp, delimiter))
    vec.push_back(tmp);
  return vec;
}

string pids_from_ppid(process_t ppid) {
  string pids;
  HANDLE hp = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  PROCESSENTRY32 pe = { 0 };
  pe.dwSize = sizeof(PROCESSENTRY32);
  if (Process32First(hp, &pe)) {
    do {
      if (pe.th32ParentProcessID == ppid) {
        pids += to_string(pe.th32ProcessID) + "|";
      }
    } while (Process32Next(hp, &pe));
  }
  if (pids.back() == '|')
    pids.pop_back();
  pids += "\0";
  CloseHandle(hp);
  return pids;
}

int main(int argc,char *argv[]) {
  if (arc >= 2) {
    string arg = argv[1];
    unsigned long ppid = stoul(arg, nullptr, 10);
    vector<string> pidVec = string_split(pids_from_ppid(ppid), '|');
    for (const string &pid : pidVec) {
      // converted to unsigned long for use 
      // unrelated to printing in a console
      cout << stoul(pid, nullptr, 10) << endl;
    }
  }
  return 0;
}

对于不仅可以在Windows上而且可以在Mac,Linux和FreeBSD上执行此操作的代码,您可以在这里找到每种平台的等效功能:https://github.com/time-killer-games/enigma-dev/tree/master/ENIGMAsystem/SHELL/Universal_System/Extensions/ProcInfo