1. 程式人生 > >win - kill process by process name

win - kill process by process name

前言

NSIS安裝程式沒有提供殺程序的API, 查資料說,要加一個第三方的外掛…
自己寫一個小程式蠻簡單,只是以前沒留存貨,還得查msdn從頭寫.
這次備一個,下次用.

實驗

// @file main.cpp
// @brief kill process by process name

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <shellapi.h>
#include <string.h>
#include <string>
#include <tchar.h>
#include <tlhelp32.h>

void fn_task();
bool kill_process_by_name(const wchar_t* psz_process_name);
bool find_process_pid(const wchar_t* psz_process_name, DWORD& dw_pid);
bool kill_process_by_pid(DWORD dw_pid);

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

	fn_task();
	return EXIT_SUCCESS;
}

void fn_task()
{
	LPWSTR* psz_Arglist = NULL;
	int nArgs = 0;
	int i = 0;
	std::wstring str_tmp = L"";
	wchar_t sz_buf[4096] = {L'\0'};
	std::wstring str_obj_to_kill = L"";

	do {
		psz_Arglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
		if (NULL == psz_Arglist)
		{
			break;
		}
		
		if ((nArgs < 2) || (NULL == psz_Arglist[1])) {
			break;
		}

		str_obj_to_kill = psz_Arglist[1];
		kill_process_by_name(str_obj_to_kill.c_str());
	} while (0);

	if (NULL != psz_Arglist) {
		LocalFree(psz_Arglist);
		psz_Arglist = NULL;
	}
}

bool kill_process_by_name(const wchar_t* psz_process_name)
{
	bool b_rc = false;
	DWORD dw_pid = 0;

	do {
		if (!find_process_pid(psz_process_name, dw_pid)) {
			break;
		}

		b_rc = kill_process_by_pid(dw_pid);
	} while (0);

	return b_rc;
}

bool find_process_pid(const wchar_t* psz_process_name, DWORD& dw_pid)
{
	bool b_rc = false;
	HANDLE hProcessSnap = NULL;
	HANDLE hProcess = NULL;
	PROCESSENTRY32 pe32;

	do {
		hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
		if (hProcessSnap == INVALID_HANDLE_VALUE) {
			break;
		}

		pe32.dwSize = sizeof(PROCESSENTRY32);
		if (!Process32First(hProcessSnap, &pe32)) {
			break;
		}

		do {
			if (0 == wcscmp(pe32.szExeFile, psz_process_name)) {
				dw_pid = pe32.th32ProcessID;
				b_rc = true;
				break;
			}
		} while(Process32Next(hProcessSnap, &pe32));
	} while (0);

	if ((NULL != hProcessSnap) && (INVALID_HANDLE_VALUE != hProcessSnap)) {
		CloseHandle( hProcessSnap );
		hProcessSnap = NULL;
	}

	return b_rc;
}

bool kill_process_by_pid(DWORD dw_pid)
{
	bool b_rc = false;
	HANDLE h_process = NULL;
    
	h_process = OpenProcess(PROCESS_ALL_ACCESS, TRUE, dw_pid);
	if (NULL != h_process) {
		b_rc = (TRUE == TerminateProcess(h_process, 0));
		CloseHandle(h_process);
		h_process = NULL;
	}

	return b_rc;
}