使用ToolHelperAPI枚举OS中所有的线程和进程
BOOL EnumProcessInfo()
{
//定义进程信息结构
PROCESSENTRY32 pe32 = {sizeof(pe32)};
//创建系统当前的进程快照
HANDLE hProcessShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessShot == INVALID_HANDLE_VALUE)
{
return false;
}
//输出进程信息到文件
ofstream fout("EnumInfo_ToolHelp_process.txt");
//循环枚举进程信息
char szBuf[300] = {0};
if (Process32First(hProcessShot, &pe32))
{
do
{
memset(szBuf, 0, sizeof(szBuf));
//把宽字符的进程名转化为ANSI字符串
WideCharToMultiByte(CP_ACP, 0, pe32.szExeFile,
wcslen(pe32.szExeFile),szBuf,sizeof(szBuf),NULL,NULL);
fout<<"Process: "<<szBuf<<endl;
fout<<'\t'<<"Usage :"<<pe32.cntUsage<<endl;
fout<<'\t'<<"ProcessID: "<<pe32.th32ProcessID<<endl;
fout<<'\t'<<"DefaultHeapID :"<<(ULONG_PTR)pe32.th32DefaultHeapID<<endl;
fout<<'\t'<<"ModuleID :"<<pe32.th32ModuleID<<endl;
fout<<'\t'<<"ThreadNum :"<<pe32.cntThreads<<endl;
fout<<'\t'<<"ParentProcessID :"<<pe32.th32ParentProcessID<<endl;
fout<<'\t'<<"PriClassBase :"<<pe32.pcPriClassBase<<endl;
} while (Process32Next(hProcessShot, &pe32));
}
fout.close();
CloseHandle(hProcessShot);
return true;
}
BOOL EnumThreadInfo()
{
//定义线程信息结构
THREADENTRY32 te32 = {sizeof(te32)};
//创建系统线程快照
HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if (hThreadSnap == INVALID_HANDLE_VALUE)
{
return false;
}
//输出线程信息到文件
ofstream fout("EnumInfo_ToolHelp_thread.txt");
//循环枚举线程信息
if (Thread32First(hThreadSnap, &te32))
{
do
{
fout<<"ThreadId:"<<te32.th32ThreadID<<endl;
fout<<'\t'<<"OwnerProcessID:"<<te32.th32OwnerProcessID<<endl;
fout<<'\t'<<"Usage :"<<te32.cntUsage<<endl;
fout<<'\t'<<"Default Priority :"<<te32.tpDeltaPri<<endl;
fout<<'\t'<<"Base Priority :"<<te32.tpBasePri<<endl;
} while (Thread32Next(hThreadSnap, &te32));
}
return TRUE;
}