如何在 Windows 上使用 C++ 从其 PID 中检索进程的完全限定路径?
最佳答案
调用 OpenProcess
获取与您的 PID 关联的进程的句柄。一旦您掌握了流程,请调用 GetModuleFileNameEx
获得其完全合格的路径。不要忘记调用CloseHandle
当您使用完进程句柄时。
这是一个执行所需调用的示例程序(将 1234 替换为您的 PID):
#include <windows.h>
#include <psapi.h> // For access to GetModuleFileNameEx
#include <tchar.h>
#include <iostream>
using namespace std;
#ifdef _UNICODE
#define tcout wcout
#define tcerr wcerr
#else
#define tcout cout
#define tcerr cerr
#endif
int _tmain(int argc, TCHAR * argv[])
{
HANDLE processHandle = NULL;
TCHAR filename[MAX_PATH];
processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, 1234);
if (processHandle != NULL) {
if (GetModuleFileNameEx(processHandle, NULL, filename, MAX_PATH) == 0) {
tcerr << "Failed to get module filename." << endl;
} else {
tcout << "Module filename is: " << filename << endl;
}
CloseHandle(processHandle);
} else {
tcerr << "Failed to open process." << endl;
}
return 0;
}
关于C++ Windows - 如何从其 PID 获取进程路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1933113/