如何使用c ++代码杀死在不同用户下运行的进程

时间:2013-09-04 04:21:20

标签: c++ kill-process

以下代码可以正常显示在不同用户下运行的所有进程(例如:notepad.exe)的进程ID。但是在当前用户下的进程却被杀死了。我需要杀死在不同用户下运行的所有进程。

#define SAMPLEAPP "notepad.exe"
void main()
{
    KillProcessByName(SAMPLEAPP);
    system("pause");
}
void KillProcessByName(const char *filename)
{
    // Taking snapshot of all processes
    HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
    //structure to capture each entry in snapshot
    PROCESSENTRY32 pEntry;
    pEntry.dwSize = sizeof (pEntry);
    //capture the first process in the list
    BOOL hRes = Process32First(hSnapShot, &pEntry);
    while (hRes)
    {
        char tempProcess[PROCESS_SIZE];// = pEntry.szExeFile;
        wcstombs(tempProcess, pEntry.szExeFile, PROCESS_SIZE);
        //if process name is equal to the process passed as argument to be killed
        if (strcmp(tempProcess, filename) == 0)
        {
            HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
                (DWORD) pEntry.th32ProcessID);
            std::cout << "Process ID of the Process " << tempProcess << " is : " << pEntry.th32ProcessID;
            if (hProcess != NULL)
            {
                // Kill the process 
                TerminateProcess(hProcess, 9);
                CloseHandle(hProcess);
            }
        }
        //Capture the next process in process snapshot
        hRes = Process32Next(hSnapShot, &pEntry);
    }
    CloseHandle(hSnapShot);
}

如果一个进程属于另一个用户,我怎么能杀死它?

1 个答案:

答案 0 :(得分:0)

右键单击您的程序,然后选择“以管理员身份运行”。