Skip to content

Instantly share code, notes, and snippets.

@dscho dscho/kill-process-tree.c
Last active Aug 29, 2015

Embed
What would you like to do?
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <tlhelp32.h>
static int get_process_tree(DWORD *list, int len, int max_len)
{
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 entry;
int i;
memset(&entry, 0, sizeof(entry));
entry.dwSize = sizeof(entry);
if (!Process32First(snapshot, &entry))
return len;
do {
for (i = len - 1; i >= 0; i--)
if (list[i] == entry.th32ParentProcessID) {
list[len++] = entry.th32ProcessID;
if (len >= max_len) {
fprintf(stderr, "Warning: many pids "
"found, stopping...\n");
return len;
}
}
} while (Process32Next(snapshot, &entry));
return len;
}
int main(int argc, char **argv)
{
DWORD list[1024];
int len = 0, i;
if (argc < 2) {
fprintf(stderr, "Usage: %s <pid>\n", argv[0]);
exit(1);
}
list[len++] = (int) atoi(argv[1]);
len = get_process_tree(list, len, sizeof(list) / sizeof(*list));
for (i = len - 1; i >= 0; i--) {
HANDLE process =
OpenProcess(PROCESS_ALL_ACCESS, FALSE, list[i]);
fprintf(stderr, "Killing %d\n", list[i]);
if (process) {
TerminateProcess(process, 1);
CloseHandle(process);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.