C++ 获取进程所在目录(进程全路径)
打开windows任务管理器,会看到很多的进程在运行,随机挑选一个,如何通过c++代码获取某一个进程的所在全路径呢?这也是在windows软件开发中经常遇到的需求。
通过进程名获取进程全路径
由于可能很多进程叫同一个名字,所以获得的结果也有可能是多个
#include <windows.h> #include <string> #include <vector> #include <tlhelp32.h> #include <Shlwapi.h> #pragma comment(lib, "Shlwapi.lib") void GetProcessPath(const std::wstring& process_name, std::vector<std::wstring>& process_path) { PROCESSENTRY32 pe32; pe32.dwSize = sizeof(pe32); HANDLE hSnapShot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnapShot == INVALID_HANDLE_VALUE) return; if (!::Process32First(hSnapShot, &pe32)) { ::CloseHandle(hSnapShot); return; } do { if (StrNCmp(process_name.c_str(), (LPWSTR)pe32.szExeFile, process_name.size()) == 0) { HANDLE hSnapShot2 = ::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pe32.th32ProcessID); if (hSnapShot2 == INVALID_HANDLE_VALUE) continue; MODULEENTRY32 me32; me32.dwSize = sizeof(MODULEENTRY32); if (!::Module32First(hSnapShot2, &me32)) { ::CloseHandle(hSnapShot2); continue; } process_path.push_back((const wchar_t*)me32.szExePath); ::CloseHandle(hSnapShot2); } } while (::Process32Next(hSnapShot, &pe32)); ::CloseHandle(hSnapShot); } int main() { std::vector<std::wstring> process_path; GetProcessPath(L"QiDian.exe", process_path); return 0; }
通过进程id获取进程全路径
#include <windows.h> #include <string> #include <Psapi.h> #pragma comment(lib,"psapi.lib") bool GetPathByProcessId(DWORD process_id, std::wstring& process_path) { HANDLE hProcess = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, process_id); if (hProcess == NULL) return false; wchar_t szPath[MAX_PATH] = { 0 }; ::GetModuleFileNameEx(hProcess, NULL, szPath, MAX_PATH); process_path.assign(szPath); return true; } int main() { std::wstring process_path; bool ret = GetPathByProcessId(33368, process_path); return 0; }