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

问题描述 投票:1回答:1

在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);
}
c++ visual-c++ windows-10 createprocess
1个回答
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.comTime-killer-gamesenigma-devtreemasterENIGMAsystemSHELLUniversal_SystemExtensionsProcInfo。

© www.soinside.com 2019 - 2024. All rights reserved.