C++重启进程教程
C++重启进程
步骤:
1、查找需要重启进程的进程id
2、启动需要重启的进程
3、杀死第一步进程id的进程
代码:
1、查找需要重启的进程的进程id
//通过进程名查找进程Id
bool GRPCClient::FindProcess(std::wstring strProcessName, DWORD& nPid)
{
TCHAR tszProcess[64] = { 0 };
lstrcpy(tszProcess, 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);
return true;
}
} while (Process32Next(hSnapshot, &ps));
CloseHandle(hSnapshot);
return false;
}
2、启动进程
//启动进程
bool GRPCClient::StartPrcess(std::wstring strProcessName)
{
TCHAR tszProcess[64] = { 0 };
lstrcpy(tszProcess, 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;
ShellExecuteEx(&shellInfo);
return true;
}
3、杀死进程
//杀死进程
bool GRPCClient::KillProcess(DWORD dwPid)
{
printf("Kill进程Pid = %d\n", dwPid);
//关闭进程
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;
}
到头来,依旧是风尘肮脏违心愿