bTagTiger
bTagTiger

Reputation: 1321

How to Get List of Thread IDs for Current Process

EnumProcess or CreateToolhelp32Snapshot functions help us getting process informations, include Process IDs.

But I want to know getting thread id list of current process.

DWORD GetMainThreadId(DWORD pId)
{
    LPVOID lpThId;

    _asm
    {
        mov eax, fs:[18h]
        add eax, 36
        mov [lpThId], eax
    }

    HANDLE hProcess = OpenProcess(PROCESS_VM_READ, FALSE, pId);
    if(hProcess == NULL)
        return NULL;

    DWORD tId;
    if(ReadProcessMemory(hProcess, lpThId, &tId, sizeof(tId), NULL) == FALSE)
    {
        CloseHandle(hProcess);
        return NULL;
    }

    CloseHandle(hProcess);

    return tId;
}

This code is to get main thread id, but I wanna get other thread modules and terminate it except main thread.

Is there any api functions or method?

My OS:Windows 7 Ultimate

Dev Tool: Visual Studio 2008

Upvotes: 1

Views: 6772

Answers (2)

arimaknp
arimaknp

Reputation: 1

You can use thread snapshot of the current process and iterate complete list of thread associated with the process if you know the process id of your application:

bool GetProcessThreads(DWORD PID) {
  HANDLE thread_snap = INVALID_HANDLE_VALUE;
  THREADENTRY32 te32;

  // take a snapshot of all running threads
  thread_snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
  if (thread_snap == INVALID_HANDLE_VALUE) {
    printf("Invalid Handle Value");
    return(FALSE);
  }

  // fill in the size of the structure before using it. 
  te32.dwSize = sizeof(THREADENTRY32);

  // retrieve information about the first thread,
  // and exit if unsuccessful
  if (!Thread32First(thread_snap, &te32)) {
    printf("Thread32First Error");
    CloseHandle(thread_snap);
    return(FALSE);
  }

  // now walk the thread list of the system,
  // and display thread ids of each thread
  // associated with the specified process
  do {
    if (te32.th32OwnerProcessID == PID)
      printf("THREAD ID: 0x%08X",te32.th32ThreadID);
  } while (Thread32Next(thread_snap, &te32));

  // clean up the snapshot object.
  CloseHandle(thread_snap);
  return(TRUE);
}

Then you can call the above function in main or any other place as below:

void main() {
  GetProcessThreads(PID) // write the process id of your application here
}

Upvotes: 0

W.B.
W.B.

Reputation: 5525

Have a look at Thread Walking.

Basically, you have to call Thread32First and call Thread32Next until you hit the wall.

Upvotes: 3

Related Questions