在 Win32 API 中,给定 PID,如何确定磁盘上可执行文件的路径? [英] In the Win32 API, given a PID, how can I determine path on disk to the executable?
问题描述
在 Win32 中,我获得了某个正在运行的进程的进程 ID.现在我想确定进程的可执行文件所在的文件系统路径.
In Win32, I've obtained a process id for a certain running process. Now I'd like to determine the path on the file system where the executable for the process resides.
例如.如果tasklist"显示图像名称"为foobar.exe",PID 为 1234.可执行文件位于 c:\Program Files (x86)\Acme Corp\foobar.exe
eg. if "tasklist" shows the "image name" to be "foobar.exe" and the PID to be 1234. The executable is located in c:\Program Files (x86)\Acme Corp\foobar.exe
哪个 Win32 API 调用将接受 PID 1234 并为我提供路径c:\Program Files (x86)\Acme Corp\foobar.exe"?
Which Win32 API call will accept the PID 1234 and give me the path "c:\Program Files (x86)\Acme Corp\foobar.exe"?
推荐答案
您应该使用 OpenProcess 打开进程以获取进程句柄,然后使用该句柄使用 GetModuleFileNameEx API 函数获取路径.
You should open the process using OpenProcess to get a process handle and then use the handle to get path using GetModuleFileNameEx API function.
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, _PID_);
if (hProcess)
{
TCHAR path[MAX_PATH];
if (GetModuleFileNameEx(hProcess, NULL, path, sizeof(path)))
{
MessageBox(0, path, "The path", MB_ICONINFORMATION);
}
CloseHandle(hProcess);
}
如果我没记错的话,使用PROCESS_QUERY_INFORMATION | PROCESS_VM_READ"就足以获取路径检索的进程句柄.如果失败,则使用 PROCESS_ALL_ACCESS.
If I remember correctly, using "PROCESS_QUERY_INFORMATION | PROCESS_VM_READ" will be enough to get process handle for path retrieve. If it failed, use PROCESS_ALL_ACCESS then.
这篇关于在 Win32 API 中,给定 PID,如何确定磁盘上可执行文件的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!