進程查殺

    工做中有時候會用到根據進程的PID殺進程,或是根據進程名殺進程的情形。windows

    網上找到一段比較有參考價值的代碼。api

// 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/9840076app

相關文章
相關標籤/搜索