GetProcessHandleCount 中的值不正确
我遇到了函数 GetProcessHandleCount() 的奇怪行为。 首先,我按照 msdn 中的描述拍摄系统中所有进程的快照:
HANDLE hProcessSnap;
HANDLE hProcess;
PROCESSENTRY32 pe32;
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
pe32.dwSize = sizeof( PROCESSENTRY32 );
if( !Process32First( hProcessSnap, &pe32 ) )
{
CloseHandle( hProcessSnap );
return 0;
}
然后我遍历进程的快照,并使用函数计算打开的句柄 GetProcessHandleCount:
int count_of_handles=0;
DWORD dwHandleCount=0;
do {
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION,FALSE,pe32.th32ProcessID);
GetProcessHandleCount(hProcess,&dwHandleCount);
count_of_handles+=dwHandleCount;
if( hProcess != NULL )
CloseHandle( hProcess );
} while( Process32Next( hProcessSnap, &pe32 ) );
我在Windows 7 x64中检查了这个程序。程序显示 count_of_handles ~16000,但实际上该值约为 100 000(如果相信 Windows 任务管理器)。
然后我在 Windows XP x32(由 VMWare)中执行该程序,count_of_handles 约为 9000(但实际上约为 8000)。
我的代码有什么问题吗?谢谢。
I faced with strange behavior of function GetProcessHandleCount().
At first I take a snapshot of all processes in the system as it is described in msdn:
HANDLE hProcessSnap;
HANDLE hProcess;
PROCESSENTRY32 pe32;
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
pe32.dwSize = sizeof( PROCESSENTRY32 );
if( !Process32First( hProcessSnap, &pe32 ) )
{
CloseHandle( hProcessSnap );
return 0;
}
Then I walk the snapshot of processes, and count up open handles by using function
GetProcessHandleCount:
int count_of_handles=0;
DWORD dwHandleCount=0;
do {
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION,FALSE,pe32.th32ProcessID);
GetProcessHandleCount(hProcess,&dwHandleCount);
count_of_handles+=dwHandleCount;
if( hProcess != NULL )
CloseHandle( hProcess );
} while( Process32Next( hProcessSnap, &pe32 ) );
I checked this program in Windows 7 x64. Program displayed count_of_handles ~16000, but really this value was ~100 000 (if believe in Windows Task Manager).
Then I executed this program in Windows XP x32 (by VMWare), and count_of_handles was ~9000 (but in real it was ~8000).
What is wrong with my code? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一方面,
GetProcessHandleCount
可能会返回零(表示错误)。这可以解释为什么结果低于您的预期。这可能是由OpenProcess 引起的
失败(您也不检查)。For one thing,
GetProcessHandleCount
might return zero (which signifies an error). This could explain coming to a result lower than what you expect. This might be caused in turn byOpenProcess
failing (you don't check for that either).以及Jon 的原因、任务管理器中的值1< /sup> 包括内核中打开的句柄 - 这些不会包含在跨进程的总数中。
1 对于这种事情 Process Explorer 是更有效。包括能够列出每个进程以及内核中的打开句柄,以及 Process Explorer 列表中的
系统
伪进程。As well as Jon's reason, the value from Task Manager1 includes handles open in the kernel – these will not be included in your total across processes.
1 For this kind of thing Process Explorer is far more effective. Including being able to list open handles per process and in the kernel, the
system
pseudo-process in Process Explorer's listing.