用C++语言遍历windows系统中的所有进程,并能用树状结构显示进程之间的父子关系,需要详细的代码实现
时间: 2023-03-29 18:04:38 浏览: 95
数据结构 图的遍历 C++实现.pdf
您好,以下是用 C 语言遍历 Windows 系统中的所有进程,并能用树状结构显示进程之间的父子关系的详细代码实现:
#include <windows.h>
#include <stdio.h>
void printProcessTree(DWORD processID, int depth);
int main()
{
// 获取系统中第一个进程的 ID
DWORD processID = ;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, );
PROCESSENTRY32 processEntry;
processEntry.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(snapshot, &processEntry))
{
processID = processEntry.th32ProcessID;
}
CloseHandle(snapshot);
// 遍历进程树
printProcessTree(processID, );
return ;
}
void printProcessTree(DWORD processID, int depth)
{
// 打印当前进程的信息
HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
if (process != NULL)
{
// 获取进程的名称
char processName[MAX_PATH] = "";
GetModuleBaseName(process, NULL, processName, MAX_PATH);
// 打印进程的信息
for (int i = ; i < depth; i++)
{
printf(" ");
}
printf("|- %s (PID: %u)\n", processName, processID);
// 关闭进程句柄
CloseHandle(process);
}
// 遍历当前进程的子进程
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, );
PROCESSENTRY32 processEntry;
processEntry.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(snapshot, &processEntry))
{
do
{
if (processEntry.th32ParentProcessID == processID)
{
printProcessTree(processEntry.th32ProcessID, depth + 1);
}
} while (Process32Next(snapshot, &processEntry));
}
CloseHandle(snapshot);
}
希望能够帮助到您!
阅读全文