C++ 实现 查找进程, 杀死进程, 启动进程, 进程重启
头文件:
#include <Windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <ShellAPI.h>
查找进程: 就是调用windowApi遍历所有启动进程, 实现如下
bool FindProcess(std::string strProcessName, DWORD& nPid) { TCHAR tszProcess[64] = { 0 }; lstrcpy(tszProcess, _T(strProcessName.c_str())); //查找进程 STARTUPINFO st; PROCESS_INFORMATION pi; PROCESSENTRY32 ps; HANDLE hSnapshot; memset(&st, 0, sizeof(STARTUPINFO)); st.cb = sizeof(STARTUPINFO); memset(&ps, 0, sizeof(PROCESSENTRY32)); ps.dwSize = sizeof(PROCESSENTRY32); memset(&pi, 0, sizeof(PROCESS_INFORMATION)); // 遍历进程 hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnapshot == INVALID_HANDLE_VALUE) return false; if (!Process32First(hSnapshot, &ps)) return false; do { if (lstrcmp(ps.szExeFile, tszProcess) == 0) { //找到制定的程序 nPid = ps.th32ProcessID; CloseHandle(hSnapshot); printf("找到进程: %s\n", tszProcess); return true; //getchar(); //return dwPid; } } while (Process32Next(hSnapshot, &ps)); CloseHandle(hSnapshot); return false; }
杀死进程: 就是通过遍历所有的启动的进程, 然后查找进程ID, 调用winapi将其杀死, 代码实现如下
bool KillProcess(DWORD dwPid) { printf("Kill进程Pid = %d\n", dwPid); getchar(); //关闭进程 HANDLE killHandle = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION | // Required by Alpha PROCESS_CREATE_THREAD | // For CreateRemoteThread PROCESS_VM_OPERATION | // For VirtualAllocEx/VirtualFreeEx PROCESS_VM_WRITE, // For WriteProcessMemory); FALSE, dwPid); if (killHandle == NULL) return false; TerminateProcess(killHandle, 0); return true; }
启动进程: 就是给出进程名绝对路径, 然后调用winapi启动
bool StartPrcess(std::string strProcessName) { TCHAR tszProcess[64] = { 0 }; lstrcpy(tszProcess, _T(strProcessName.c_str())); //启动程序 SHELLEXECUTEINFO shellInfo; memset(&shellInfo, 0, sizeof(SHELLEXECUTEINFO)); shellInfo.cbSize = sizeof(SHELLEXECUTEINFO); shellInfo.fMask = NULL; shellInfo.hwnd = NULL; shellInfo.lpVerb = NULL; shellInfo.lpFile = tszProcess; // 执行的程序名(绝对路径) shellInfo.lpParameters = NULL; shellInfo.lpDirectory = NULL; shellInfo.nShow = SW_MINIMIZE; //SW_SHOWNORMAL 全屏显示这个程序 shellInfo.hInstApp = NULL; printf("程序自动重启中.... \n"); ShellExecuteEx(&shellInfo); return true; }
程序重启流程: 1: 先查找需要重启的程序进程Id
2: 启动需要重启的程序
3: 杀死第一步的进程id
代码上面已实现