Windows平台 C++进程树获取实现

本文介绍了如何在Windows平台上使用C++实现获取进程树的功能。通过系统API获取进程信息,包括进程名、ID和父进程ID,利用递归构建进程树。首先从孤儿进程开始,使用map作为容器标记进程ID,再通过遍历和排序建立父子关系。程序以MFC对话框展示,详细阐述了关键步骤和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在写一个小项目,涉及到查找和结束进程树的功能实现,通过系统API能够获取到的信息有进程名,进程ID,父进程ID等,所以通过一个递归操作可以获取到一棵完整的进程树。但由于进程ID是系统随机给予的,并没有什么规律,所有最理想的做法是从最祖父进程(孤儿进程)开始查找子进程,再查找孙子进程…… 这种思路。

我的程序使用MFC对话框写的,具体效果如下图。


首先是进程信息存放的结构体

//进程结构体
typedef struct TASKMGRDLL_API tagProcessItem
{
	DWORD dwProcessID;		//进程ID
	DWORD dwModuleID;		//模块ID
	HANDLE hProcess;		//进程句柄
	DWORD dwcntThreads;		//线程数
	DWORD dwParentProcessID;//父进程ID
	string szExeFile;		//进程文件名
	string szExeFilePath;	//进程文件全路径
	BOOL bParentAvailableFlag;//父进程是否存在
	int nProcTreeIndex;		//进程树子孙标记
	//模块列表
	vector <ModuleItemA> theModuleList;
	
	//拷贝函数
	void CopyItemFrom(tagProcessItem &theItem)
	{
		this ->dwProcessID = theItem.dwProcessID;
		this ->dwParentProcessID = theItem.dwParentProcessID;
		this ->dwModuleID = theItem.dwModuleID;
		this ->dwcntThreads = theItem.dwcntThreads;
		this ->szExeFile = theItem.szExeFile;
		this ->szExeFilePath = theItem.szExeFilePath;
		this ->hProcess = theItem.hProcess;
		this ->bParentAvailableFlag = theItem.bParentAvailableFlag;
		this ->nProcTreeIndex = theItem.nProcTreeIndex;
		this ->theModuleList = theItem.theModuleList;
	}
	void CopyItemTo(tagProcessItem &theItem)
	{
		theItem.dwProcessID = this ->dwProcessID;
		theItem.dwParentProcessID = this ->dwParentProcessID;
		theItem.dwModuleID = this ->dwModuleID;
		theItem.dwcntThreads = this ->dwcntThreads;
		theItem.szExeFile = this ->szExeFile;
		theItem.szExeFilePath = this ->szExeFilePath;
		theItem.hProcess = t
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值