Linux kill all processes with name

This function will read each process’s status file in /proc and kill the process if it’s name matches the name of the processes you want to kill. Returns false if there was an error opening or reading the status file. I will include in this in the next version of my AXCEL library.

#include <sys/types.h>
#include <signal.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

bool killp(const char* name) {
	pid_t p;
	size_t i, j;
	char* s = (char*)malloc(264);
	char buf[128];
	FILE* st;
	DIR* d = opendir("/proc");
	if (d == NULL) { free(s); return false; }
	struct dirent* f;
	while ((f = readdir(d)) != NULL) {
		if (f->d_name[0] == '.') continue;
		for (i = 0; isdigit(f->d_name[i]); i++);
		if (i < strlen(f->d_name)) continue;
		strcpy(s, "/proc/");
		strcat(s, f->d_name);
		strcat(s, "/status");
		st = fopen(s, "r");
		if (st == NULL) { closedir(d); free(s); return false; }
		do {
			if (fgets(buf, 128, st) == NULL) { fclose(st); closedir(d); free(s); return false; }
		} while (strncmp(buf, "Name:", 5));
		for (j = 5; isspace(buf[j]); j++);
		*strchr(buf, '\n') = 0;
		if (!strcmp(&(buf[j]), name)) {
			sscanf(&(s[6]), "%d", &p);
			kill(p, SIGKILL);
	return true;

2 thoughts on “Linux kill all processes with name

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: