简体   繁体   English

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

[英]How to Get List of Thread IDs for Current Process

EnumProcess or CreateToolhelp32Snapshot functions help us getting process informations, include Process IDs. EnumProcess 或 CreateToolhelp32Snapshot 函数帮助我们获取进程信息,包括进程 ID。

But I want to know getting thread id list of current process.但我想知道获取当前进程的线程 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;
}

This code is to get main thread id, but I wanna get other thread modules and terminate it except main thread.这段代码是为了获取主线程 id,但我想获取其他线程模块并终止它,除了主线程。

Is there any api functions or method?有没有api函数或方法?

My OS:Windows 7 Ultimate我的操作系统:Windows 7 Ultimate

Dev Tool: Visual Studio 2008开发工具:Visual Studio 2008

Have a look at Thread Walking .看看线程行走

Basically, you have to call Thread32First and call Thread32Next until you hit the wall.基本上,您必须调用Thread32First并调用Thread32Next直到您碰壁。

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:如果您知道应用程序的进程 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);
}

Then you can call the above function in main or any other place as below:然后你可以在 main 或任何其他地方调用上面的函数,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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