Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerating threads in Windows

How can I enumerate all of the threads in a process given a HANDLE to the process (or a process ID)? I'm interested in doing this so I can further do an EnumThreadWindows on each thread.

like image 479
bdonlan Avatar asked Jul 30 '09 14:07

bdonlan


2 Answers

Enumerating threads in a process at MSDN Blogs.

Code snippet from there:

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

int __cdecl main(int argc, char **argv)
{
 HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
 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)) {
       printf("Process 0x%04x Thread 0x%04x\n",
             te.th32OwnerProcessID, te.th32ThreadID);
     }
   te.dwSize = sizeof(te);
   } while (Thread32Next(h, &te));
  }
  CloseHandle(h);
 }
 return 0;
}
like image 150
nik Avatar answered Oct 12 '22 15:10

nik


The ToolHelp library gives an API for snapshotting processes and enumerating their threads (amongst other properties). See MSDN for details.

like image 39
Steve Gilham Avatar answered Oct 12 '22 16:10

Steve Gilham