OpenThread为不同的线程ID返回相同的句柄

时间:2015-06-28 18:01:26

标签: winapi

使用从here获取的以下代码以及一些添加来获取线程句柄的代码,OpenThread为进程中的每个线程返回相同的句柄但ID不同。

#include <stdio.h>
#include <windows.h>
#include <tlhelp32.h>

int __cdecl main(int argc, char **argv)
{
 HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
 HANDLE hThread;
 if (h != INVALID_HANDLE_VALUE) {
  THREADENTRY32 te;
  te.dwSize = sizeof(te);
  if (Thread32First(h, &te)) {
   do {
     if (te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) +
                      sizeof(te.th32OwnerProcessID)) {
       hThread = OpenThread(THREAD_QUERY_INFORMATION, FALSE, te.th32ThreadID);
       printf("Process 0x%04x Thread 0x%04x Handle %d\n",
             te.th32OwnerProcessID, te.th32ThreadID, hThread);
       CloseHandle(hThread);
     }
   te.dwSize = sizeof(te);
   } while (Thread32Next(h, &te));
  }
  CloseHandle(h);
 }
 return 0;
}

一些输出:

Process 0x10fc Thread 0x2270 Handle 68
Process 0x10fc Thread 0x13d4 Handle 68
Process 0x10fc Thread 0x071c Handle 68
Process 0x10fc Thread 0x2140 Handle 68
Process 0x10fc Thread 0x20d4 Handle 68
Process 0x1b70 Thread 0x21e8 Handle 68
Process 0x1c7c Thread 0x1d18 Handle 68
Process 0x1c7c Thread 0x10b8 Handle 68
Process 0x0d84 Thread 0x1fa0 Handle 68

那么,如果所有函数都具有相同的数字,我应该如何使用需要线程处理的函数?

1 个答案:

答案 0 :(得分:4)

如果您需要保持线头的手柄,请不要关闭手柄!