(See the previous (i.e. first) version of this tool.)
(See the next follow-up.)
After taking into consideration all the advice by Martin R, I ended up with the following tool for terminating all the processes with given process image names:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <TlHelp32.h>
int main(int argc, char* argv[]) {
if (argc != 2) {
fprintf(stderr, "processkiller.exe PROCESS_NAME");
return EXIT_FAILURE;
}
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (snapshot == INVALID_HANDLE_VALUE) {
fputs("Error: could not get the process snapshot.", stderr);
return EXIT_FAILURE;
}
size_t totalProcessesMatched = 0;
size_t totalProcessesTerminated = 0;
if (Process32First(snapshot, &entry)) {
do {
if (strcmp(entry.szExeFile, argv[1]) == 0) {
totalProcessesMatched++;
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE,
FALSE,
entry.th32ProcessID);
if (hProcess == NULL) {
fprintf(stderr,
"Error: could not open the process with ID = %d, "
"called \"%s\".\n",
entry.th32ProcessID,
entry.szExeFile);
} else {
BOOL terminated = TerminateProcess(hProcess, 0);
if (terminated) {
totalProcessesTerminated++;
BOOL closed = CloseHandle(hProcess);
if (!closed) {
fprintf(stderr,
"Warning: could not close a handle "
"for process ID = %d, called \"%s\".\n",
entry.th32ProcessID,
entry.szExeFile);
}
printf("Terminated process ID %d\n", entry.th32ProcessID);
}
}
}
} while (Process32Next(snapshot, &entry));
}
BOOL snapshotHandleClosed = CloseHandle(snapshot);
if (!snapshotHandleClosed) {
fputs("Warning: could not close the process snapshot.", stderr);
}
printf("Info: total matching processes: %d, total terminated: %d.\n",
totalProcessesMatched,
totalProcessesTerminated);
return EXIT_SUCCESS;
}
Critique request
Am I going anywhere? Is this tool coded properly? Am I sufficiently verbose about statistics/error information?