场景:
1.有时候需要调用外部程序,但是外部程序有可能崩溃挂起,这样这个进程就没法结束,所以再在下次调用前需要先结束之前调用的。
2.没考虑到权限问题,应该是只能终止当前用户启动的进程.
[cpp] view plaincopy
- #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;
- }
时间: 2024-10-15 14:12:00