首页 > 代码库 > 进程查杀

进程查杀

    工作中有时候会用到根据进程的PID杀进程,或是根据进程名杀进程的情形。

    网上找到一段比较有参考价值的代码。

// Process.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <stdio.h>  #include <windows.h>  #include <winbase.h>  #include <tlhelp32.h>  #pragma comment(lib,"kernel32.lib")  #pragma comment(lib,"advapi32.lib")  void EnableDebugPriv() {      HANDLE hToken;      TOKEN_PRIVILEGES tkp;      OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);      LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);      tkp.PrivilegeCount = 1;      tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;      AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, NULL, NULL);      CloseHandle(hToken);  }  int pskill(int id)   //根据进程ID杀进程  {      HANDLE hProcess=NULL;      //打开目标进程      hProcess=OpenProcess(PROCESS_TERMINATE,FALSE,id);      if (hProcess==NULL) {          wprintf(L"\nOpen Process fAiled:%d\n",GetLastError());          return -1;      }      //结束目标进程      DWORD ret=TerminateProcess(hProcess,0);      if(ret==0) {          wprintf(L"%d",GetLastError());      }      return -1;  }  int main() {      //进程列举      HANDLE hSnApshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);      if (hSnApshot != INVALID_HANDLE_VALUE) {          PROCESSENTRY32 te = { sizeof(te) };          BOOL f0k = Process32First(hSnApshot, &te);          for (; f0k; f0k = Process32Next(hSnApshot, &te)) {              wprintf(L"Pid: %d %s\n", te.th32ProcessID, te.szExeFile);          }      }      CloseHandle(hSnApshot);      //杀进程      wprintf(L"the process‘s id which you want to kill:");      int id = 0;      wscanf(L"%d", &id);      EnableDebugPriv(); //提升权限      pskill(id);      return 0;  }

工程源码:http://download.csdn.net/download/qq_33892166/9840076

进程查杀