Code Repo    |     RSS
MD's Technical Sharing



Monday, October 13, 2008

Kill a process given its executable name.

BOOL KillProcessByName(const TCHAR* p_strEXE)
{
printf("Attempting to terminate ");
OutputDebugString(p_strEXE);
printf("\n");

HANDLE hSnapShot
= NULL;
PROCESSENTRY32 pEntry
= {0};

// Get the snapshot of the system
hSnapShot
= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (hSnapShot != INVALID_HANDLE_VALUE)
{
pEntry
.dwSize = sizeof(pEntry);

//Get first process
if (Process32First(hSnapShot, &pEntry))
{
TCHAR strTempExe
[MAX_PATH];
_tcscpy(strTempExe, pEntry.szExeFile);

printf("Found: ");
OutputDebugString(strTempExe);
printf("\n");

//found process on the first attempt, kill it
if (_tcscmp(strTempExe, p_strEXE) == 0) goto KillProcess;

//Iterate through all other processes
while (Process32Next(hSnapShot, &pEntry))
{
_tcscpy(strTempExe, pEntry.szExeFile);

printf("Found: ");
OutputDebugString(pEntry.szExeFile);
printf("\n");

//we have found our process;
if (_tcscmp(strTempExe, p_strEXE) == 0) goto KillProcess;
}
}
else
{
printf("Process32First FAILED. Error %d\n", GetLastError());
}
}
else
{
printf("Process32First FAILED. Error %d\n", GetLastError());
}

//if we are here it means process cannot be found;
goto ProcessNotFound;

KillProcess:

CloseHandle(hSnapShot);

//kill it
HANDLE hProcess
= OpenProcess(PROCESS_ALL_ACCESS, FALSE, pEntry.th32ProcessID);
if (hProcess)
{
if (::TerminateProcess(hProcess, 0))
{
printf("Process terminated.\n");
return TRUE;
}
else
{
printf("TerminateProcess FAILED. Error %d\n", GetLastError());
return FALSE;
}
}
else
{
printf("OpenProcess FAILED. Error %d\n", GetLastError());
return FALSE;
}

ProcessNotFound:
CloseHandle(hSnapShot);

printf("Specified process not found.\n");
return FALSE;
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.