简体   繁体   中英

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

Have a look at Thread Walking .

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM