1. 程式人生 > >[Windows]_[C/C++]_[WIN32根據程式名(映像名稱)終止外部程式]

[Windows]_[C/C++]_[WIN32根據程式名(映像名稱)終止外部程式]

場景:

1.有時候需要呼叫外部程式,但是外部程式有可能崩潰掛起,這樣這個程序就沒法結束,所以再在下次呼叫前需要先結束之前呼叫的。

2.沒考慮到許可權問題,應該是隻能終止當前使用者啟動的程序.

#include <stdio.h>
#include <string.h>

#include <windows.h>
#include <Tlhelp32.h>

#include <vector>

void TerminateProcessByName(PCWSTR name)
{
    DWORD pid = 0;
	
    // Create toolhelp snapshot.
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    PROCESSENTRY32W process;
    ZeroMemory(&process, sizeof(process));
    process.dwSize = sizeof(process);

	std::vector<DWORD> pids;
    // Walkthrough all processes.
    if (Process32FirstW(snapshot, &process))
    {
        do
        {
            // Compare process.szExeFile based on format of name, i.e., trim file path
            // trim .exe if necessary, etc.
            if (!wcscmp(process.szExeFile, name))
            {
               pid = process.th32ProcessID;	
			   pids.push_back(pid);
            }
        } while (Process32NextW(snapshot, &process));
    }

    CloseHandle(snapshot);
	
	size_t size = pids.size();
	for(size_t i = 0; i < size; ++i)
	{
		HANDLE one_process = OpenProcess(PROCESS_TERMINATE, FALSE, pids[i]);
		BOOL res = TerminateProcess(one_process,0);
		if(res)
		{
			WaitForSingleObject(one_process,1000);
		}
	}
}

int main(int argc, char *argv[])
{
	printf("Hello, world\n");
	
	std::vector<DWORD> pids;
	TerminateProcessByName(L"notepad.exe");

	return 0;
}