开发环境:VC6.0 + WinXp Sp2
首先,我们需要定义一些相关的结构体和常量:
|
关于NTQUERYSYSTEMINformATION的定义
typedef NTSTATUS (__stdcall *NTQUERYSYSTEMINformATION)
(IN SYSTEM_INformATION_CLASS SystemInformationClass,
IN OUT PVOID SystemInformation,
IN ULONG SystemInformationLength,
OUT PULONG ReturnLength OPTIONAL);
NTQUERYSYSTEMINformATION NtQuerySystemInformation;
在这里需要查看进程表的CLASS_INFO为5,在头文件中我定义为NT_PROCESS_LIST, 第二个参数为存放返回信息的地址,在此之前需要先为其申请一段内存.如果该段内存小了,则函数会返回STATUS_INFO_LEN_MISMATCH,在头文件中可以见到其值为0xC0000004.如果成果返回,则值为STATUS_SUCCESS即0.下面程序实现的代码:代码:
#include <stdio.h>
#include <windows.h>
#include <tchar.h>
#include "ntQuery.h"
int _tmain(void)
{
size_t blocklen = 0;
PSYSTEM_PROCESSES bufForProcessesInfo = NULL, bufNext = NULL;
NTSTATUS ns = 0;
DWORD dwPcount = 0;
HANDLE hHeap;
int i = 2;
HMODULE hNtdll = LoadLibrary(TEXT("NTDLL.DLL"));
if(hNtdll == NULL)
{
printf("LaodLibrary ntddl.dll error...\n");
return -1;
}
NTQUERYSYSTEMINformATION NtQuerySystemInformation =
(NTQUERYSYSTEMINformATION)GetProcAddress(hNtdll, TEXT("NtQuerySystemInformation"));
if(NtQuerySystemInformation == NULL)
{
printf("GetProcAddress error...\n");
return -1;
}
hHeap = GetProcessHeap();
if(hHeap == NULL)
{
printf("Get heap error...\n");
FreeLibrary(hNtdll);
return -1;
}
bufForProcessesInfo = (PSYSTEM_PROCESSES)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, BLOCK_SIZE);
if(bufForProcessesInfo == NULL)
{
printf("HeapAlloc error...\n");
FreeLibrary(hNtdll);
return -1;
}
bufNext = bufForProcessesInfo;
ns = NtQuerySystemInformation(NT_PROCESS_LIST, bufForProcessesInfo, BLOCK_SIZE, NULL);
while(ns == STATUS_INFO_LEN_MISMATCH)
{
bufNext = (PSYSTEM_PROCESSES)HeapReAlloc(hHeap, HEAP_ZERO_MEMORY, bufNext, BLOCK_SIZE * i);
if(bufForProcessesInfo == NULL)
{
printf("Relloc error..\n");
HeapFree(hHeap, HEAP_ZERO_MEMORY, bufForProcessesInfo);
FreeLibrary(hNtdll);
return -1;
}
ns = NtQuerySystemInformation(NT_PROCESS_LIST, bufNext, BLOCK_SIZE * i, NULL);
i++;
}
while(bufNext->NextEntryDelta != 0)
{
wprintf(L"PID:%.4d\tBasePriority:%.2d\t%s\n", bufNext->ProcessId, bufNext->BasePriority, bufNext->ProcessName.Buffer);
bufNext = (PSYSTEM_PROCESSES)((BYTE*)bufNext + bufNext->NextEntryDelta);
dwPcount ++;
}
_tprintf(TEXT("------------------------------------------------"\
"\nAll %d processes running...\n"), dwPcount);
HeapFree(hHeap, HEAP_ZERO_MEMORY, bufForProcessesInfo);
FreeLibrary(hNtdll);
Sleep(10000);
return 0;
}
http://www.hacker.cn/News/xtaq/2006-9/16/0691616290358737_2.shtml