如何获取当前进程的线程ID列表

时间:2013-06-27 03:50:08

标签: c++ windows winapi threadpool

EnumProcess或CreateToolhelp32Snapshot函数可帮助我们获取流程信息,包括流程ID。

但我想知道获取当前进程的线程ID列表。

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

此代码是获取主线程ID,但我想获得其他线程模块并终止它,除了主线程。

是否有api功能或方法?

我的操作系统:Windows 7旗舰版

开发工具:Visual Studio 2008

2 个答案:

答案 0 :(得分:3)

查看Thread Walking

基本上,您必须致电Thread32First并致电Thread32Next,直到您碰壁。

答案 1 :(得分:0)

如果您知道应用程序的进程ID,则可以使用当前进程的线程快照并迭代与该进程关联的线程的完整列表:

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

然后您可以在主要位置或以下任何其他位置调用上述函数:

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