VC kill the specified process (Windows)

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/mao0514/article/details/88757217

A. Through the system command to kill the process

Command to kill the process through the system, black window flashes

bool KillProcess(vector<string> &processNameVec)
{
    bool result = false;
    string strProcess;
    HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    PROCESSENTRY32 pInfo;
    pInfo.dwSize = sizeof(pInfo);
    Process32First(hSnapShot, &pInfo);
    do
    {
        wstring wstrTemp = pInfo.szExeFile;
        strProcess = UnicodeToAscii(wstrTemp);

        bool bIn = false;
        for (int i = 0; i < processNameVec.size(); i++) {
            if (processNameVec[i] == strProcess) {
                bIn = true;
            }
        }
        if (bIn) {
            result = true;
            string cmd;
            char cmdData[128] = { 0 };
            sprintf_s(cmdData, "taskkill /F /PID %d /T", pInfo.th32ProcessID);
            cmd = cmdData;
            system(cmd.c_str());
        }
    } while (Process32Next(hSnapShot, &pInfo));
    return result;
}

II. By TerminateProcess kill the process
 

bool KillProcessEx(vector<string> &processNameVec)
{
    HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

    PROCESSENTRY32 pe;
    pe.dwSize = sizeof(PROCESSENTRY32);

    if (!Process32First(hSnapShot, &pe))
    {
        return false;
    }

    while (Process32Next(hSnapShot, &pe))
    {
        wstring strTemp = pe.szExeFile;
        string strProcessTemp = UnicodeToAscii(strTemp);

        bool bIn = false;
        for (int i = 0; i < processNameVec.size(); i++)
        {
            if (processNameVec[i] == strProcessTemp)
            {
                bIn = true;
            }
        }

        if (bIn)
        {
            DWORD dwProcessID = pe.th32ProcessID;
            HANDLE hProcess = ::OpenProcess(PROCESS_TERMINATE, FALSE, dwProcessID);
            ::TerminateProcess(hProcess, 0);
            CloseHandle(hProcess);
        }
    }

    return true;
}

 

Guess you like

Origin blog.csdn.net/mao0514/article/details/88757217