用户输入关键字,然后遍历当前系统进程,结束具有指定关键字的进程,技术含量不高,练手而已。
// KillVmware.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Tlhelp32.h>
#include <Psapi.h>
#include <shlwapi.h>
#include <strsafe.h>
#pragma comment(lib, "Psapi.lib")
#pragma comment(lib, "shlwapi.lib")
int _tmain(int argc, _TCHAR* argv[])
{
TCHAR szDstName[MAX_PATH] = {0};
std::wcout << _T("input target process flag:") << std::endl;
while(std::wcin >> szDstName)
{
/*DWORD dwProcesses[1024] = {0};
DWORD dwNeeded, dwProcess;
if (!EnumProcesses(dwProcesses, sizeof(dwProcesses), &dwNeeded))
return 1;
dwProcess = dwNeeded / sizeof(DWORD);
TCHAR szProcessName[MAX_PATH];
for (DWORD i = 0; i < dwProcess; ++i)
{
if (dwProcesses[i])
{
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE, dwProcesses[i]);
if (hProcess)
{
ZeroMemory(szProcessName, MAX_PATH);
GetModuleBaseName(hProcess, NULL, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR));
if (lstrlen(szProcessName))
std::wcout << i << _T("->\t") << szProcessName << std::endl;
if (StrStrI(szProcessName, _T("vmware")) && StrCmpI(szProcessName, _T("KillVmware.exe")))
{
CloseHandle(hProcess);
hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, dwProcesses[i]);
std::wcout << _T("kill process ") << szProcessName << (::TerminateProcess(hProcess, 0) ? _T("succeed") : _T("failed")) << std::endl;
}
CloseHandle(hProcess);
}
}
}*/
HANDLE handle = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
std::pair<DWORD, TCHAR*> targetIDs[1024];
int index = 0;
if (INVALID_HANDLE_VALUE != handle)
{
PROCESSENTRY32 entry;
entry.dwSize = sizeof(entry);
if (::Process32First(handle, &entry))
{
TCHAR szCurName[MAX_PATH] = {0};
GetModuleBaseName(GetCurrentProcess(), NULL, szCurName, sizeof(szCurName)/sizeof(TCHAR));
do
{
if (StrStrI(entry.szExeFile, szDstName) && 0 != StrCmpI(entry.szExeFile, szCurName))
{
targetIDs[index].first = entry.th32ProcessID;
targetIDs[index].second = new TCHAR[MAX_PATH];
ZeroMemory(targetIDs[index].second, MAX_PATH);
//memcpy_s(targetIDs[index].second, MAX_PATH, entry.szExeFile, sizeof(entry.szExeFile));
StringCchCopy(targetIDs[index].second, MAX_PATH, entry.szExeFile);
++index;
}
} while (::Process32Next(handle, &entry));
}
::CloseHandle(handle);
}
for (int i = 0; i < index; ++i)
{
std::wcout << _T("kill process ") << targetIDs[i].second <<
(::TerminateProcess(OpenProcess(PROCESS_TERMINATE, FALSE, targetIDs[i].first), 0) ? _T(" succeed") : _T(" failed")) << std::endl;
delete []targetIDs[i].second;
}
std::wcout << _T("input target process flag:") << std::endl;
}
//system("pause");
return 0;
}
开始是用的第一种方式,调试过程中发现只能枚举当前用户进程,无法获取系统进程,后来又换了第二种方法,win7下需要以管理员权限运行。