我有以下代码(它获取所有进程,然后在其中搜索正则表达式模式,用于更大的恶意软件检测个人项目的代码),该代码执行我想要的,但唯一的问题是它使用 100% 的 CPU,怎么办我做错了吗?内存分配不好?我用 MS Visual Studio 2010 (cl.exe /EHsc mycode.cpp) 编译它
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <tlhelp32.h>
#include <psapi.h>
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <iterator>
#include <regex>
using namespace std;
#pragma comment(lib, "psapi.lib")
void PrintProcessNameAndID(DWORD);
void find_locs(HANDLE process);
void ListProcesses();
int main(int argc, char **argv) {
ListProcesses();
}
void find_locs(HANDLE process) {
unsigned char *p = NULL;
MEMORY_BASIC_INFORMATION info;
for ( p = NULL;
VirtualQueryEx(process, p, &info, sizeof(info)) == sizeof(info);
p += info.RegionSize )
{
std::string buffer;
if (info.State == MEM_COMMIT &&
(info.Type == MEM_MAPPED || info.Type == MEM_PRIVATE))
{
DWORD bytes_read;
buffer.resize(info.RegionSize);
ReadProcessMemory(process, p, &buffer[0], info.RegionSize, &bytes_read);
buffer.resize(bytes_read);
const std::tr1::regex rx("([\\w-+]+(?:\\.[\\w-+]+)*@(?:[\\w-]+\\.)+[a-zA-Z]{2,7})");
std::tr1::match_results<std::string::const_iterator> res;
std::tr1::regex_search(buffer, res, rx);
ofstream myfile;
myfile.open ("proc.txt", ios::app);
for (unsigned int i=0; i<res.size(); ++i)
{
std::cout << res[i] << std::endl;
myfile << res[i] << "\n";
}
myfile.close();
}
}
}
void ListProcesses()
{
DWORD aProcesses[1024];
DWORD cbNeeded;
DWORD cProcesses;
unsigned int i;
if (!EnumProcesses(aProcesses,sizeof(aProcesses),&cbNeeded))
return;
cProcesses = cbNeeded / sizeof(DWORD);
for ( i = 0; i < cProcesses; i++ )
{
PrintProcessNameAndID(aProcesses[i]);
}
}
void PrintProcessNameAndID(DWORD processID)
{
TCHAR szProcessName[MAX_PATH]; // = TEXT("<unknown>");
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
if (NULL != hProcess)
{
HMODULE hMod;
DWORD cbNeeded;
if (EnumProcessModules(hProcess, &hMod, sizeof(hMod),
&cbNeeded))
{
GetModuleBaseName(hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR));
}
}
_tprintf(TEXT("pid: %u file: %s\n"), processID, szProcessName);
find_locs(hProcess);
CloseHandle(hProcess);
}
感谢帮助!