使用windows api
#include <psapi.h> #include <tlhelp32.h> void get_process_file_path(DWORD process_id, char* path, int path_size) { HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_id); GetModuleFileNameExA(process, NULL, path, path_size); CloseHandle(process); } bool get_exe_path(LPCWSTR processName, char* path, int path_size) { PROCESSENTRY32 processInfo; processInfo.dwSize = sizeof(processInfo); HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (processesSnapshot == INVALID_HANDLE_VALUE) { printf("Invalid handle value "); return false; } Process32First(processesSnapshot, &processInfo); if (!wcscmp(processName, processInfo.szExeFile)) { CloseHandle(processesSnapshot); printf("Found process "); return true; } while (Process32Next(processesSnapshot, &processInfo)) { if (!wcscmp(processName, processInfo.szExeFile)) { DWORD pid = processInfo.th32ProcessID; CloseHandle(processesSnapshot); get_process_file_path(pid, path, path_size); return true; } } CloseHandle(processesSnapshot); printf("Process NOT found. "); return false; }
此处要轮询每个进程,稍微费时,不适合几秒钟就做一次的情况