C++.线程状态

typedef LONG NTSTATUS;
typedef LONG KPRIORITY;
#define STATUS_SUCCESS                  ((NTSTATUS) 0x00000000)
#define NT_SUCCESS(Status)              ((NTSTATUS)(Status) >= 0)
#define STATUS_INFO_LENGTH_MISMATCH     ((NTSTATUS)0xC0000004L)
typedef struct _CLIENT_ID {
    HANDLE UniqueProcess;
    HANDLE UniqueThread;
} CLIENT_ID, *PCLIENT_ID;
typedef struct _SYSTEM_THREAD_INFORMATION {
    LARGE_INTEGER KernelTime;
    LARGE_INTEGER UserTime;
    LARGE_INTEGER CreateTime;
    ULONG WaitTime;
    PVOID StartAddress;
    CLIENT_ID ClientId;
    KPRIORITY Priority;
    LONG BasePriority;
    ULONG ContextSwitches;
    ULONG ThreadState;
    ULONG WaitReason;
} SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION;
typedef struct _UNICODE_STRING {
    USHORT Length;
    USHORT MaximumLength;
    PWSTR  Buffer;
} UNICODE_STRING, *PUNICODE_STRING;
typedef struct _VM_COUNTERS {
    SIZE_T PeakVirtualSize;
    SIZE_T VirtualSize;
    ULONG PageFaultCount;
    SIZE_T PeakWorkingSetSize;
    SIZE_T WorkingSetSize;
    SIZE_T QuotaPeakPagedPoolUsage;
    SIZE_T QuotaPagedPoolUsage;
    SIZE_T QuotaPeakNonPagedPoolUsage;
    SIZE_T QuotaNonPagedPoolUsage;
    SIZE_T PagefileUsage;
    SIZE_T PeakPagefileUsage;
} VM_COUNTERS;
typedef VM_COUNTERS *PVM_COUNTERS;
typedef struct _SYSTEM_PROCESS_INFORMATION {
    ULONG            NextEntryDelta;
    ULONG            ThreadCount;
    ULONG            Reserved1[6];
    LARGE_INTEGER   CreateTime;
    LARGE_INTEGER   UserTime;
    LARGE_INTEGER   KernelTime;
    UNICODE_STRING ProcessName;
    KPRIORITY        BasePriority;
    ULONG            ProcessId;
    ULONG            InheritedFromProcessId;
    ULONG            HandleCount;
    ULONG            Reserved2[2];
    VM_COUNTERS        VmCounters;
    IO_COUNTERS        IoCounters;
    SYSTEM_THREAD_INFORMATION Threads[5];
} SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION;
typedef enum _SYSTEM_INFORMATION_CLASS {
    SystemBasicInformation,
    SystemProcessorInformation,             // obsolete...delete
    SystemPerformanceInformation,
    SystemTimeOfDayInformation,
    SystemPathInformation,
    SystemProcessInformation,
    SystemCallCountInformation,
    SystemDeviceInformation,
    SystemProcessorPerformanceInformation,
    SystemFlagsInformation,
    SystemCallTimeInformation,
    SystemModuleInformation,
    SystemLocksInformation,
    SystemStackTraceInformation,
    SystemPagedPoolInformation,
    SystemNonPagedPoolInformation,
    SystemHandleInformation,
    SystemObjectInformation,
    SystemPageFileInformation,
    SystemVdmInstemulInformation,
    SystemVdmBopInformation,
    SystemFileCacheInformation,
    SystemPoolTagInformation,
    SystemInterruptInformation,
    SystemDpcBehaviorInformation,
    SystemFullMemoryInformation,
    SystemLoadGdiDriverInformation,
    SystemUnloadGdiDriverInformation,
    SystemTimeAdjustmentInformation,
    SystemSummaryMemoryInformation,
    SystemMirrorMemoryInformation,
    SystemPerformanceTraceInformation,
    SystemObsolete0,
    SystemExceptionInformation,
    SystemCrashDumpStateInformation,
    SystemKernelDebuggerInformation,
    SystemContextSwitchInformation,
    SystemRegistryQuotaInformation,
    SystemExtendServiceTableInformation,
    SystemPrioritySeperation,
    SystemVerifierAddDriverInformation,
    SystemVerifierRemoveDriverInformation,
    SystemProcessorIdleInformation,
    SystemLegacyDriverInformation,
    SystemCurrentTimeZoneInformation,
    SystemLookasideInformation,
    SystemTimeSlipNotification,
    SystemSessionCreate,
    SystemSessionDetach,
    SystemSessionInformation,
    SystemRangeStartInformation,
    SystemVerifierInformation,
    SystemVerifierThunkExtend,
    SystemSessionProcessInformation,
    SystemLoadGdiDriverInSystemSpace,
    SystemNumaProcessorMap,
    SystemPrefetcherInformation,
    SystemExtendedProcessInformation,
    SystemRecommendedSharedDataAlignment,
    SystemComPlusPackage,
    SystemNumaAvailableMemory,
    SystemProcessorPowerInformation,
    SystemEmulationBasicInformation,
    SystemEmulationProcessorInformation,
    SystemExtendedHandleInformation,
    SystemLostDelayedWriteInformation,
    SystemBigPoolInformation,
    SystemSessionPoolTagInformation,
    SystemSessionMappedViewInformation,
    SystemHotpatchInformation,
    SystemObjectSecurityMode,
    SystemWatchdogTimerHandler,
    SystemWatchdogTimerInformation,
    SystemLogicalProcessorInformation,
    SystemWow64SharedInformation,
    SystemRegisterFirmwareTableInformationHandler,
    SystemFirmwareTableInformation,
    SystemModuleInformationEx,
    SystemVerifierTriageInformation,
    SystemSuperfetchInformation,
    SystemMemoryListInformation,
    SystemFileCacheInformationEx,
    MaxSystemInfoClass  // MaxSystemInfoClass should always be the last enum
} SYSTEM_INFORMATION_CLASS;
typedef NTSTATUS(__stdcall *ZWQUERYSYSTEMINFORMATION)(
    __in SYSTEM_INFORMATION_CLASS SystemInformationClass,
    __out_bcount_opt(SystemInformationLength) PVOID SystemInformation,
    __in ULONG SystemInformationLength,
    __out_opt PULONG ReturnLength
    );
typedef enum _KTHREAD_STATE {
    Initialized,
    Ready,
    Running, /*2*/
    Standby,
    Terminated,
    Waiting,  
    Transition,
    DeferredReady,
    GateWait
} KTHREAD_STATE;
INT GetThreadState(IN DWORD dwTid, IN DWORD dwPid)
{
    INT ret = -1;
    try
    {
        ZWQUERYSYSTEMINFORMATION ZwQuerySystemInformation = (ZWQUERYSYSTEMINFORMATION)GetProcAddress(LoadLibrary(_T("ntdll.dll")), "ZwQuerySystemInformation");
        if (ZwQuerySystemInformation)
        {
            BYTE *pbt = 0;
            DWORD dw = 0x1000;
            NTSTATUS ntsta = 0;
            for (; dw < INT_MAX; dw *= 2)
            {
                if (pbt)
                {
                    delete pbt;
                    pbt = 0;
                }
                pbt = new BYTE[dw];
                if (pbt)
                {
                    ntsta = ZwQuerySystemInformation(SystemProcessInformation, pbt, dw, 0);
                    if (NT_SUCCESS(ntsta))
                    {
                        break;
                    }
                }
            }
            if (pbt && NT_SUCCESS(ntsta))
            {
                PSYSTEM_PROCESS_INFORMATION pInfo = (PSYSTEM_PROCESS_INFORMATION)pbt;
                SYSTEM_PROCESS_INFORMATION item = { 0 };
                for (; ret == -1;)
                {
                    if (dwPid == pInfo->ProcessId)
                    {
                        for (DWORD i = 0; i < pInfo->ThreadCount; ++i)
                        {
                            if ((HANDLE)dwTid == pInfo->Threads[i].ClientId.UniqueThread)
                            {
                                ret = pInfo->Threads[i].ThreadState;
                            }
                        }
                    }
                    if (pInfo->NextEntryDelta == 0)
                    {
                        break; /*下一节点值0则结束循环*/
                    }
                    pInfo = (PSYSTEM_PROCESS_INFORMATION)((DWORD)pInfo + pInfo->NextEntryDelta);
                }
                delete pbt;
                pbt = 0;
            }
        }
    }
    catch (...)
    {
        OutputDebugStringA(__FUNCTION__);
    }
    return ret;
}

#include <TlHelp32.h>
#include <vector>
BOOL TraversalThread1(OUT std::vector<THREADENTRY32> &vec)
{
    /************************************************************************/
    /*
    typedef struct tagTHREADENTRY32
    {
    DWORD   dwSize;
    DWORD   cntUsage;
    DWORD   th32ThreadID;       // this thread
    DWORD   th32OwnerProcessID; // Process this thread is associated with
    LONG    tpBasePri;
    LONG    tpDeltaPri;
    DWORD   dwFlags;
    } THREADENTRY32;
    */
    /************************************************************************/
    vec.clear();
    try
    {
        HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
        if (hSnap != INVALID_HANDLE_VALUE)
        {
            THREADENTRY32 item;
            item.dwSize = sizeof(item);
            if (Thread32First(hSnap, &item))
            {
                do
                {
                    vec.push_back(item);
                } while (Thread32Next(hSnap, &item));
            }
            CloseHandle(hSnap);
        }
    }
    catch (...)
    {
        OutputDebugStringA(__FUNCTION__);
        return 0;
    }
    return vec.size() > 0;
}

int main()
{
    std::vector<THREADENTRY32> vec;
    std::cout << TraversalThread1(vec) << endl;
    INT state = -1;
    for each (THREADENTRY32 var in vec)
    {
        state = GetThreadState(var.th32ThreadID, var.th32OwnerProcessID);
        //if (9764 == var.th32OwnerProcessID)
        //{
        //  printf("%08X %08X|%d %d", var.th32ThreadID, var.th32OwnerProcessID, var.th32OwnerProcessID, state);
        //  printf("\r\n");
        //}
        printf("%08X %08X|%d %d", var.th32ThreadID, var.th32OwnerProcessID, var.th32OwnerProcessID, state);
        printf("\r\n");
    }

    return 0;
}
上一篇:坚果云+svn实现异地非局域网个人代码版本管理


下一篇:1_class