natli
natli

Reputation: 3822

All process handles are the same (CreateToolhelp32Snapshot)

For some reason all window handles I retrieve are the same..

handles

I don't see why this is the case.

int classname::functionname(const char* processname)
{
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if (stricmp(entry.szExeFile, processname) == 0)
            {  
                HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION + PROCESS_VM_READ + PROCESS_TERMINATE, FALSE, entry.th32ProcessID);
                cout << "Name: " << processname << " Handle: " << hProcess << endl;
                CloseHandle(hProcess);
            }
        }
    }

    CloseHandle(snapshot);

    return 0;
}

Upvotes: 0

Views: 2178

Answers (1)

Andr&#233; Caron
Andr&#233; Caron

Reputation: 45234

AFAIK, there's no reason why the system would not re-use process handles. Have you tried commenting out the CloseHandle(hProcess); bit temporarily, forcing the system not to re-use the handles, to see if the process handles are different?

Edit

That does it for me. Play with the following program. Just edit the value of REUSE_PROCESS_HANDLE to see the effect.

#undef UNICODE
#include <Windows.h>
#include <Tlhelp32.h>

#include <iostream>
using namespace std;

#define REUSE_PROCESS_HANDLE 0

int main ()
{
    const char processname[] = "chrome.exe";
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if (stricmp(entry.szExeFile, processname) == 0)
            {  
                HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION + PROCESS_VM_READ + PROCESS_TERMINATE, FALSE, entry.th32ProcessID);
                cout << "Name: " << processname << " Handle: " << hProcess << endl;
#if REUSE_PROCESS_HANDLE
                CloseHandle(hProcess);
#endif
            }
        }
    }

    CloseHandle(snapshot);
}

Upvotes: 1

Related Questions