开发者

Incorrect values from GetProcessHandleCount

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 cou开发者_如何学JAVAnt_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, 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 by OpenProcess failing (you don't check for that either).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜