[英]Retrieving process running dir from PID
Trying to retrieve the running directory of a process using the PID. 尝试使用PID检索进程的运行目录。 I am obtaining the PID using FindWindow()
and GetWindowThreadProcessId()
which results in the same process ID as shown in task manager, so I assume it to be correct. 我正在使用FindWindow()
和GetWindowThreadProcessId()
获取PID,其结果与任务管理器中显示的进程ID相同,因此我认为它是正确的。
When using GetModuleFileNameEx()
, instead of resulting in a path, I get what seems to be a memory address. 当使用GetModuleFileNameEx()
,我得到的似乎是一个内存地址,而不是生成路径。
auto wnd = FindWindow(nullptr, L"prog");
while (wnd == nullptr)
{
wnd = FindWindow(nullptr, L"prog");
}
TCHAR fBuf[MAX_PATH]; // buffer for path
DWORD procId; // process id
GetWindowThreadProcessId(wnd, &procId); // get process id
std::cout << procId << std::endl; // results in correct pid
auto procHdl = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, procId); // create handle for process
if (procHdl != NULL) {
if (GetModuleFileNameEx(procHdl, 0, fBuf, MAX_PATH) == 0) {
std::cerr << "Failed to get module filename." << std::endl;
}
else {
std::cout << "Module filename is: " << fBuf << std::endl;
}
CloseHandle(procHdl);
}
Sample output is: 样本输出为:
10488
Module filename is: 008CF93C
I have had the same result using GetProcessImageFileNname()
too. 我也使用GetProcessImageFileNname()
获得了相同的结果。
To get the directory of a program, first use GetModuleFileNameEx to get the program path, and your directory will start from the first character to the last backslash found. 要获取程序的目录,请首先使用GetModuleFileNameEx获取程序路径,然后您的目录将从第一个字符开始到找到的最后一个反斜杠开始。
Example: 例:
Program is: "C:\\Windows\\notepad.exe"; 程序为:“ C:\\ Windows \\ notepad.exe”;
Directory is: "C:\\Windows"; 目录是:“ C:\\ Windows”;
In code: 在代码中:
DWORD pid = 104;
CHAR ProgramFile[MAX_PATH];
std::string DirectoryPath;
HANDLE hProcess = OpenProcess(PROCESS_VM_READ|PROCESS_QUERY_INFORMATION, FALSE, pid);
GetModuleFileNameExA(hProcess, NULL, ProgramFile, MAX_PATH);
DirectoryPath = ProgramFile;
DirectoryPath = DirectoryPath.substr(0, DirectoryPath.find_last_of('\\'));
std::cout << "ProgramFile: " << ProgramFile << endl;
std::cout << "Directory: " << DirectoryPath.c_str();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.