1

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 Ultimate

开发工具:Visual Studio 2008

4

2 回答 2

3

看看线程行走

基本上,你必须不停地打电话Thread32FirstThread32Next直到碰壁。

于 2014-04-17T19:41:04.693 回答
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);
}

然后您可以在 main 或任何其他地方调用上述函数,如下所示:

void main() {
  GetProcessThreads(PID) // write the process id of your application here
}
于 2020-04-16T08:55:23.017 回答