c++ 通过exe路径获取pid

bool getPID(std::string exeFilePath, DWORD &pid) {
    // replace /
    for (char & i : exeFilePath) {
        i = i == '/' ? '\\' : i;
    }
    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(pe32);
    HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hProcessSnap == INVALID_HANDLE_VALUE) {
        return false;
    }
    int nameStartIndex = std::max((int)exeFilePath.rfind('/'), (int)exeFilePath.rfind('\\'));
    std::string exeFileName = exeFilePath.substr(nameStartIndex+1);
    bool flag = false;
    if (!Process32First(hProcessSnap, &pe32)) return false;
    do {
        if (std::string(pe32.szExeFile) != exeFileName) continue;
        DWORD tPID = pe32.th32ProcessID;
        HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, tPID);
        char lpExeName[MAX_PATH] = {};
        size_t lpdwSize = MAX_PATH;
        GetModuleFileNameEx(hProcess, NULL, lpExeName, lpdwSize);
        CloseHandle(hProcess);
        std::string tExeFilePath(lpExeName);
        std::cout<<tExeFilePath << std::endl;
        if (tExeFilePath == exeFilePath) {
            pid = tPID;
            flag = true;
            break;
        }
    } while(Process32Next(hProcessSnap, &pe32));
    CloseHandle(hProcessSnap);
    return flag;
}

文章目录