所有进程句柄都是相同的(CreateToolhelp32Snapshot)

时间:2011-10-26 23:45:55

标签: c++

由于某种原因,我检索的所有窗口句柄都是相同的..

handles

我不明白为什么会这样。

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;
}

1 个答案:

答案 0 :(得分:1)

AFAIK,没有理由说系统不会重复使用进程句柄。您是否尝试暂时注释掉CloseHandle(hProcess);位,强制系统不要重复使用句柄,以查看进程句柄是否不同?

修改

这对我来说。玩下面的程序。只需编辑REUSE_PROCESS_HANDLE的值即可查看效果。

#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);
}