C语言获取进程路径:使用Win32 API实现
#include <windows.h> #include <tlhelp32.h> //需要包含tlhelp32.h头文件
// 获取指定进程的路径 BOOL GetProcessPathByName(const WCHAR* processName, WCHAR* processPath, DWORD processPathLength) { HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) { return FALSE; }
PROCESSENTRY32 processEntry = { 0 };
processEntry.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(snapshot, &processEntry))
{
do
{
if (wcscmp(processEntry.szExeFile, processName) == 0)
{
wcscpy_s(processPath, processPathLength, processEntry.szExeFile);
PathRemoveFileSpec(processPath);
PathAddBackslash(processPath);
wcscat_s(processPath, processPathLength, processName);
CloseHandle(snapshot);
return TRUE;
}
} while (Process32Next(snapshot, &processEntry));
}
CloseHandle(snapshot);
return FALSE;
}
int main() { WCHAR processName[] = L"notepad.exe"; WCHAR processPath[MAX_PATH] = { 0 };
if (GetProcessPathByName(processName, processPath, MAX_PATH))
{
wprintf(L"The path of %s is %s\n", processName, processPath);
}
else
{
wprintf(L"Failed to get the path of %s\n", processName);
}
return 0;
}
这段代码演示了如何使用Windows API中的CreateToolhelp32Snapshot和Process32First/Process32Next函数来遍历系统中所有的进程,并且通过进程名称进行匹配,最终获取到进程路径。
原文地址: http://www.cveoy.top/t/topic/nnJF 著作权归作者所有。请勿转载和采集!