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.
For one thing,
GetProcessHandleCountmight return zero (which signifies an error). This could explain coming to a result lower than what you expect. This might be caused in turn byOpenProcessfailing (you don’t check for that either).