process 可能會有多個 thread,於是要列舉 thread 時,必須要指定是哪個 process ,所以要給的必要參數是 process id。先看相關 struct

typedef struct tagTHREADENTRY32 {
  DWORD dwSize; // 結構體大小
  DWORD cntUsage; // 不用,設0
  DWORD th32ThreadID; // 此 thread ID
  DWORD th32OwnerProcessID; // 擁有此 thread 之 process id
  LONG  tpBasePri; // 優先權, 0-31
  LONG  tpDeltaPri; // 不用, 設0
  DWORD dwFlags; // 不用, 設0
} THREADENTRY32, *PTHREADENTRY32;

由於若要列舉每個 process 下的每個 thread,會花很久時間,在此也建議如非必要,建議別這麼做。這裡只列出相關之副函式,若取得 PID 有問題的話,請看這篇文章

原始碼

// ==================================
// filename: ListThread.cpp
// compiler: vs2008
// author  : EdisonX (Edison.Shih.)
//   
//   **** all rights reserve ****
// ==================================
#include <windows.h>
#include <stdio.h>
#include <tlhelp32.h>

BOOL ListThread(DWORD PID)
{
        HANDLE hThread;
        THREADENTRY32 tentry;

        hThread = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
        if(hThread==INVALID_HANDLE_VALUE) {
                printf("CreateToolhelp32Snapshot fail: %d\n",GetLastError());
                return FALSE;
        }
        tentry.dwSize = sizeof(THREADENTRY32);

        if(!Thread32First(hThread, &tentry)){
                printf("Thread32First fail: %d\n",GetLastError());
                CloseHandle(hThread);
                return FALSE;
        }
        while(Thread32Next(hThread, &tentry)){
                // display
                printf("\n=============================\n");
                printf("ThreadID      :%08x\n", tentry.th32ThreadID);
                printf("ThreadOwnerPID:%08x\n", tentry.th32OwnerProcessID);
                printf("base priority :%d\n", tentry.tpBasePri);
        }
        CloseHandle(hThread);
        return TRUE;
}


// ==================================

int main()
{
        DWORD pid = GetCurrentProcessId();
        ListThread(pid);
        return 0;
}

edisonx 發表在 痞客邦 PIXNET 留言(0) 人氣()