Get process CPU Usage--ntquerysysteminformation

Source: Internet
Author: User
Tags switches



Today, we are mainly talking about a function ntquerysysteminformation (zwquerysysteminformation). Of course, you do not underestimate such a function, it provides us with a wealth of system information, but also package
Controls and settings for certain information.

The following is the prototype of this function:

typedef NTSTATUS (__stdcall *ntquerysysteminformation)     (in      system_information_class systeminformationclass , in Out  PVOID                    systeminformation,      in      ULONG                    systeminformationlength,      out     Pulong                   Returnlength  OPTIONAL);  NtQuerySystemInformation ntquerysysteminformation;

Systeminformationclass is a type of information, which probably provides more than 50 kinds of information, that is, we can use this function for about 50 kinds of system information to probe or set.
SystemInformation is a lpvoid-type pointer that provides us with the information we need to get, or the system information we need to set up.
Systeminformationlength is the length of the systeminformation, which is determined by the type of information being probed.
As for Returnlength, it is the desired length of the system return, which can usually be set to a null pointer (NULL).

First, let's look at the familiar system process/thread-related information. This topic has been discussed on the internet for many years, so I am not the cliché, hehe. Then we propose the definition of this structure type:

typedef struct _SYSTEM_PROCESSES  {ULONG          nextentrydelta;          The offset of the constituent structure sequence is ulong          threadcount;             Number of threads ulong          reserved1[6];           Large_integer  createtime;              Creation time; large_integer  usertime;                User mode (Ring 3) CPU time large_integer  kerneltime;              CPU time of kernel mode (Ring 0) unicode_string ProcessName;             Process name kpriority      basepriority;            Process priority ULONG          ProcessId;               Process identifier ULONG          Inheritedfromprocessid;  The identifier of the parent process, ulong          Handlecount;             Number of handles ULONG          reserved2[2]; Vm_counters    vmcounters;              The structure of the virtual memory, see the next io_counters    iocounters;              IO count structure, see below System_threads threads[1];              A structure array of process-dependent threads, see below}system_processes,*psystem_processes;


typedef struct _system_threads{large_integer kerneltime;               CPU kernel mode usage time Large_integer usertime;                 CPU User mode usage time large_integer createtime;               Thread creation time ULONG         WaitTime;                 Wait time pvoid         startaddress;             The virtual address of the thread start client_id     ClientId;                 Thread identifier kpriority priority     ;                 Thread priority kpriority     basepriority;             Basic priority ULONG         Contextswitchcount;       Number of environment switches thread_state State  ;                    Current state Kwait_reason  Waitreason;               Wait for cause}system_threads,*psystem_threads;


typedef struct _VM_COUNTERS{ULONG peakvirtualsize;                  Virtual Storage peak size ulong VirtualSize;                      Virtual storage size ULONG Pagefaultcount;                   Number of page faults ulong PeakWorkingSetSize;               Working Set peak size ulong WorkingSetSize;                   Working set size ulong Quotapeakpagedpoolusage;          Paged pool usage Quota peak ulong quotapagedpoolusage;              Paged Pool usage quota ulong quotapeaknonpagedpoolusage;       Nonpaged Pool Usage Quota peak ulong quotanonpagedpoolusage;           Nonpaged Pool usage quota ulong pagefileusage;                    Page file usage of ulong PeakPageFileUsage;                The page file uses peak}vm_counters,*pvm_counters;


typedef struct _io_counters{large_integer Readoperationcount;       Number of I/O read operations Large_integer Writeoperationcount;      Number of I/O write operations Large_integer Otheroperationcount;      Number of I/O other operations Large_integer Readtransfercount;        The number of I/O read data large_integer writetransfercount;       Number of I/O write data large_integer othertransfercount;       I/O other operational data number}io_counters,*pio_counters;


The above information should be more comprehensive, in the Win32 API provides us with the PSAPI (process state) and TOOLHELP32 two ways to probe the system process/thread information, in windows2k/xp/2003 support them.

Now, we take a look at the performance information of the system, the performance structure System_performance_information provides us with more than 70 kinds of system performance information, is really rich, please slowly realize ~

typedef struct _SYSTEM_PERFORMANCE_INFORMATION{LARGE_INTEGER IdleTime;           CPU idle time Large_integer readtransfercount;          Number of I/O read operations Large_integer Writetransfercount;          Number of I/O write operations Large_integer Othertransfercount;          Number of I/O other operations ulong Readoperationcount;         Number of I/O read data ulong Writeoperationcount;         Number of I/O write data ulong Otheroperationcount;              I/O other operational Data number ULONG Availablepages;         Number of pages available ulong Totalcommittedpages;            Total pages submitted in ULONG Totalcommitlimit;              Number of submitted pages ulong Peakcommitment;                  Page submission peak ULONG PageFaults;             Number of page faults ulong Writecopyfaults;            Copy-on-write number of faults ulong transitionfaults; Number of soft page faults ulong Reserved1;            ULONG Demandzerofaults;                   Demand 0 fault number ulong Pagesread;                 Number of read pages ulong Pagereadios; Read page I/O operand ulong RESERVED2[2];        ULONG Pagefilepageswritten;        Page file number of pages ulong Pagefilepagewriteios;      Write page file operand ulong Mappedfilepageswritten;          Written map file page ulong Mappedfilewriteios;              Write-mapped file operand ulong Pagedpoolusage;           The paged pool uses ulong Nonpagedpoolusage;             Non-paged pool using ulong Pagedpoolallocs;              Paged pool allocation of ulong pagedpoolfrees;          Paged pool release of ULONG Nonpagedpoolallocs;           Nonpaged pool allocation of ulong nonpagedpoolfress;         Nonpaged Pool free condition ulong totalfreesystemptes;              System Page Table key releases total ulong systemcodepage;      Operating system code page ULONG Totalsystemdriverpages;        Paging driver pages ulong Totalsystemcodepages; Total number of operating system code pages ulong Smallnonpagedlookasidelistallocatehits; ULONG smallpagedlookasidelistallocatehits;                   ULONG Reserved3;          ULONG Mmsystemcachepage;    System cache pages ULONG Pagedpoolpage;          Paged pool pages ulong Systemdriverpage;             Paging drive page ULONG fastreadnowait;               Asynchronous fast read number ulong fastreadwait;       Synchronous fast reads the number of ULONG Fastreadresourcemiss;        Rapid Read resource conflict number ULONG fastreadnotpossible;          Fast read failure number ULONG fastmdlreadnowait;            Asynchronous MDL Fast Read number ulong fastmdlreadwait;    Synchronous MDL Fast Read number ulong Fastmdlreadresourcemiss;     MDL Read Resource conflict number ULONG fastmdlreadnotpossible;              MDL Read failure number ULONG mapdatanowait;                Number of asynchronous map data ulong mapdatawait;          Number of simultaneous map data ulong Mapdatanowaitmiss;            Number of asynchronous map data collisions ulong Mapdatawaitmiss;         Number of synchronization map data collisions ulong Pinmappeddatacount;              Number of map data contained ulong Pinreadnowait;                Contain the number of asynchronous reads ULONG pinreadwait;          contain the number of simultaneous reads ULONG Pinreadnowaitmiss;            Contain the number of asynchronous read collisions ulong Pinreadwaitmiss; Count the number of simultaneous read collisions ulong CopyreadnowAit               Asynchronous copy read number ulong copyreadwait;         Number of simultaneous copies read ULONG Copyreadnowaitmiss;           Asynchronous copy read failure number ULONG Copyreadwaitmiss;              Synchronous copy read failure number ULONG mdlreadnowait;                Asynchronous MDL read number ulong mdlreadwait;          Synchronous MDL reads ULONG Mdlreadnowaitmiss;            Asynchronous MDL read failure number ULONG Mdlreadwaitmiss;               Synchronous MDL Read failure number ULONG Readaheadios;               Number of forward read operations ulong Lazywriteios;             Number of lazy write operations ulong Lazywritepages;                Number of lazy write page files ulong dataflushes;                  Cache flush count ULONG DataPages;            Cache refresh pages ULONG Contextswitches;          Number of environment switches ulong Firstleveltbfills;         Number of buffer fills in the first layer ulong secondleveltbfills;                 Number of buffer fills in the second layer ulong Systemcall; Number of system calls}system_performance_information,*psystem_performance_information;


What you see now is the use of the system processor provided by the fabric system_processor_times, including the usage time and number of interrupts in various situations:

typedef struct __system_processor_times{large_integer IdleTime;               Idle time large_integer kerneltime;             Kernel mode time Large_integer usertime;               User mode time Large_integer dpctime;                Delay process call time Large_integer Interrupttime;          Interrupt time ulong         Interruptcount;         Number of interrupts}system_processor_times,*psystem_processor_times;


Page file usage, System_pagefile_information provides the relevant information you need:

typedef struct _SYSTEM_PAGEFILE_INFORMATION{ULONG Netxentryoffset;                The offset of the next structure is ulong currentsize;                    Current page file size ulong totalused;                      Number of page files currently in use ULONG peakused;                       The number of page file peaks currently in use unicode_string FileName;              The file name of the page file}system_pagefile_information,*psystem_pagefile_information;


The usage of the system cache is described in the information provided by structure System_cache_information:

typedef struct _SYSTEM_CACHE_INFORMATION{ULONG systemcachewssize;              Cache size ULONG Systemcachewspeaksize;          Cache peak size ulong Systemcachewsfaults;            Number of cache page faults ulong Systemcachewsminimum;           Cache Minimum page size ulong systemcachewsmaximum;           Cache Maximum page size ulong transitionsharedpages;          Number of shared pages ulong Transitionsharedpagespeak;      Shared Page peak number ulong reserved[2];} System_cache_information,*psystem_cache_information;


Appendix: (All the full source code, you can go to our FZ5FZ homepage to download).

1.t-pmlist header File Source code:

DWORD enumprocess () {psystem_processes psystemproc; hmodule hntdll = NULL; LPVOID Lpsysteminfo = Null;dword dwnumberbytes = Max_info_buf_len;dword Dwtotalproce SS = 0;dword Dwreturnlength; NTSTATUS Status; Longlong Lltemptime;__try{hntdll = LoadLibrary ("NtDll.dll"), if (Hntdll = = NULL) {printf ("LoadLibrary Error:%d\n" , GetLastError ()); __leave;} NtQuerySystemInformation = (ntquerysysteminformation) GetProcAddress (Hntdll, "ntquerysysteminformation"); NtQuerySystemInformation = = NULL) {printf ("GetProcAddress for ntquerysysteminformation Error:%d\n", GetLastError ()); _ _leave;} Lpsysteminfo = (LPVOID) malloc (dwnumberbytes); Status = NtQuerySystemInformation (nt_processthread_info,lpsysteminfo,dwnumberbytes,&dwreturnlength); Status = = Status_info_length_mismatch) {printf ("status_info_length_mismatch\n"); __leave;} else if (Status! = status_success) {printf ("NtQuerySystemInformation Error:%d\n", GetLastError ()); __leave;} printf ("%-20s%6s%7s%8s%6s%7s%7s%13s\n", "ProcessName", "PID", "PPID", "Wssize", "Prio.", "Thread", "Handle", "CPU Time" );p rintf ("-------------------------------------------------------------------\ n");p Systemproc = (psystem_ PROCESSES) lpsysteminfo;while (Psystemproc->nextentrydelta! = 0) {if (Psystemproc->processid! = 0) {wprintf (L "%- 20s ", psystemproc->processname.buffer);} else{wprintf (L "%-20s", L "System Idle Process");} printf ("%6d", Psystemproc->processid);p rintf ("%7d", Psystemproc->inheritedfromprocessid);p rintf ("%7dK", psystemproc->vmcounters.workingsetsize/1024);p rintf ("%6d", psystemproc->basepriority);p rintf ("%7d", Psystemproc->threadcount);p rintf ("%7d", psystemproc->handlecount); lltemptime = psystemproc-> Kerneltime.quadpart + psystemproc->usertime.quadpart;lltemptime/= 10000;printf ("%3d:", LlTempTime/(60 * 60 * 1000))  Lltemptime%= * 1000;printf ("%.2d:", Lltemptime/(+)), Lltemptime%= * 1000;printf ("%.2d.", Lltemptime /1000); Lltemptime%= 1000;printf ("%.3d", Lltemptime);p rintf ("\ n");d wtotalprocess++;p systemproc = (psystem_processes) (( char *) Psystemproc + Psystemproc->nextentrydelta);} printf ("-------------------------------------------------------------------\ n");p rintf ("\ntotal%d Process (es)!\ N\n ", dwtotalprocess);p rintf (" pid\t ==> process identification\n ");p rintf (" ppid\t ==> Parent Process identification\n ");p rintf (" wssize\t ==> working Set size\n ");p rintf (" prio.\t ==> Base priority\n ");p rintf (" Thread\t ==> Thread count\n ");p rintf (" handle\t ==> Handle count\n ");p rintf (" CPU time ==> Processor time\n ");} __finally{if (Lpsysteminfo! = NULL) {free (lpsysteminfo);} if (hntdll! = NULL) {freelibrary (Hntdll);}} return 0;}


http://blog.csdn.net/wwwwly/article/details/7083561

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Get process CPU Usage--ntquerysysteminformation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.