任务是:通过可执行文件名查找进程ID。
调用应用程序是 32 位的,查找进程可以是 32 位或 64 位
解决方案:
#include <string>
#include <iostream>
#include <windows.h>
#include <Tlhelp32.h>
#include <psapi.h>
#pragma comment(lib, "psapi.lib")
size_t r_wcsstr(const wchar_t* str, const wchar_t* search)
{
for (size_t i = wcslen(str) - wcslen(search); i > 0; --i)
{
if (wcsstr(str + i, search) != NULL)
return i + 1;
}
return -1;
}
bool find_process_1(const std::wstring& name, DWORD& pid)
{
DWORD aProcesses[1024] { 0 };
DWORD cbNeeded { 0 };
DWORD cProcesses { 0 };
unsigned int i;
if (EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded) == 0)
return false;
cProcesses = cbNeeded / sizeof(DWORD);
for (i = 0; i < cProcesses; i++)
{
WCHAR module_name[MAX_PATH] { 0 };
HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, FALSE, aProcesses[i]);
if (process == NULL ||
GetProcessImageFileNameW(process, module_name, sizeof(module_name) / sizeof(WCHAR)) == 0)
continue;
size_t pos = r_wcsstr(module_name, name.c_str());
if (pos != -1)
{
pid = aProcesses[i];
return true;
}
}
return false;
}
bool find_process_2(const std::wstring& name, DWORD& pid)
{
HANDLE snapshot = INVALID_HANDLE_VALUE;
PROCESSENTRY32 process_entry = { 0 };
process_entry.dwSize = sizeof(process_entry);
bool found = false;
snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (snapshot == INVALID_HANDLE_VALUE)
return false;
BOOL success = Process32First(snapshot, &process_entry);
while (success == TRUE)
{
if (_wcsicmp(process_entry.szExeFile, name.c_str()) == 0)
{
pid = process_entry.th32ProcessID;
CloseHandle(snapshot);
return true;
}
success = Process32Next(snapshot, &process_entry);
}
CloseHandle(snapshot);
return false;
}
int main(int argc, WCHAR **argv)
{
unsigned long pid { 0 };
unsigned long long total { 0 };
for (int i = 0; i < 1000; ++i)
{
unsigned long long start = GetTickCount64();
find_process_1(L"Calculator.exe", pid);
total += (GetTickCount64() - start);
}
std::wcout << L"Total: " << total << L"\tper call: " << total / 1000. << std::endl;
total = 0;
for (int i = 0; i < 1000; ++i)
{
unsigned long long start = GetTickCount64();
find_process_2(L"Calculator.exe", pid);
total += (GetTickCount64() - start);
}
std::wcout << L"Total: " << total << L"\tper call: " << total / 1000. << std::endl;
return 0;
}
Total: 4094 per call: 4.094
Total: 4688 per call: 4.688
有比OpenProcesses
+更快的方法GetProcessImageFileName
吗?
我还发现QueryFullProcessImageName
了可以稍微减少 find_process_1 时间的函数
UPD1:使用 NtQuerySystemInformation 代码的解决方案是错误的,请参阅解决方案
#include <winternl.h>
#pragma comment(lib,"ntdll.lib")
struct _SYSTEM_PROCESS_INFO
{
ULONG NextEntryOffset;
ULONG NumberOfThreads;
LARGE_INTEGER Reserved[3];
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ImageName;
ULONG BasePriority;
HANDLE ProcessId;
HANDLE InheritedFromProcessId;
};
bool find_process_3(const std::wstring& name, DWORD& pid)
{
_SYSTEM_PROCESS_INFO* spi;
size_t size = 1024*1024;
PVOID buffer = VirtualAlloc(NULL, 1024 * 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
ULONG real_size {0};
NTSTATUS ret = NtQuerySystemInformation(SystemProcessInformation, buffer, size, &real_size);
bool found {false};
if (NT_SUCCESS(ret) == true)
{
spi = (_SYSTEM_PROCESS_INFO*)buffer;
while(spi->NextEntryOffset)
{
if (spi->ImageName.Buffer != nullptr && _wcsicmp(spi->ImageName.Buffer, name.c_str()) == 0)
{
pid = (long)spi->ProcessId;
found = true;
break;
}
spi = (_SYSTEM_PROCESS_INFO*)((LPBYTE)spi + spi->NextEntryOffset);
}
}
VirtualFree(buffer, 0, MEM_RELEASE);
return found;
}
和结果:
Total: 4562 per call: 4.562 // OpenProcess + GetProcessImageFileName
Total: 4453 per call: 4.453 // OpenProcess + QueryFullProcessImageName
Total: 5188 per call: 5.188 // CreateToolhelp32Snapshot
Total: 2797 per call: 2.797 // NtQuerySystemInformation
看起来真的更快,谢谢@RbMm