//APIEnumProcess
//列举线程
/*头文件*/
#include<windows.h>
#include<stdio.h>
#include<Psapi.h>
#pragma comment (lib,"Psapi.lib") //EnumProcess() 在这个库里面
bool EnableDebugPrivilege() {
HANDLE hToken;
LUID sedebugnameValue;
TOKEN_PRIVILEGES tkp;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY|TOKEN_ALL_ACCESS, &hToken))
{
return FALSE;
}
if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &sedebugnameValue))
{
CloseHandle(hToken);
return false;
}
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Luid = sedebugnameValue;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(tkp), NULL, NULL))
{
CloseHandle(hToken);
return false; }
return true; }
int EnumProcessDIY(void)
{
DWORD aProcess[1024], //进程数组
cbNeeded, //
cProcess; //进程总数
TCHAR* procName=NULL; //进程名
procName = new TCHAR[MAX_PATH]; //开辟内存空间
unsigned int i; //循环使用
HANDLE hProcess[1024]; //进程句柄
ZeroMemory(aProcess, sizeof(DWORD));
//开始枚举,枚举失败返回 1
if( !EnumProcesses( aProcess, sizeof(aProcess), &cbNeeded))
{
return 1;
}
cProcess = cbNeeded /sizeof(DWORD); //进程总数
printf("num %d",cProcess);
for( i = 0; i < cProcess; i++)
{
//获取每个进程的句柄
//hProcess[i]=OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, TRUE, aProcess[i]);
hProcess[i]=OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, aProcess[i]);
DWORD error = GetLastError();
//获得进程名称,保存在 procName
GetModuleFileNameEx(hProcess[i], NULL, procName, MAX_PATH);
error = GetLastError();
//打印进程ID 和 进程名
if(aProcess[i] == 0 || aProcess[i] ==4)
{
printf("\nProcess:%u SYSTEM\n%d\n", aProcess[i],GetLastError());
}
else
printf("\nProcess:%u %s\n%d\n", aProcess[i], procName,GetLastError());
//不能获取的是SYSTEM 进程 或者 本地服务进程
//进程0为所有进程的父进程
//本机进程4 656 1000 1252 1612 1996为系统进程
}
return 0;
}
int main(void)
{
DWORD dwProcessID;
EnableDebugPrivilege();
EnumProcessDIY();
while( dwProcessID ) // 0 表示结束
{
//输入提示
printf("Input a Process ID to end\n");
scanf("%ld", &dwProcessID);
if(dwProcessID == 0)
break;
HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, TRUE, dwProcessID);
//if( TerminateProcess( OpenProcess ( PROCESS_ALL_ACCESS, FALSE, dwProcessID), NULL ))
if( TerminateProcess( handle, NULL ) )
{
//结束进程失败,以及系统进程不能结束
printf("Error:%d", GetLastError());
}
//关闭句柄
CloseHandle(handle);
EnumProcessDIY(); //结束进程后,重新枚举进程
}
printf("%ld\n",dwProcessID);
getchar();
return 0;
}