aboutsummaryrefslogtreecommitdiff
path: root/lib/lib.c
diff options
context:
space:
mode:
authorRob Landley <rob@landley.net>2012-02-18 15:12:41 -0600
committerRob Landley <rob@landley.net>2012-02-18 15:12:41 -0600
commitff9ee8fc15e1a41bffe06bfcee30368e7c117601 (patch)
tree4806b88fe328eb96c4a9f7df41dd5c8859a56117 /lib/lib.c
parent3c1104ff57f22495a7711eabb4c0d3b5cda4a982 (diff)
downloadtoybox-ff9ee8fc15e1a41bffe06bfcee30368e7c117601.tar.gz
Add killall by Andreas Heck, and factor out common pid code to lib.h.
Diffstat (limited to 'lib/lib.c')
-rw-r--r--lib/lib.c55
1 files changed, 55 insertions, 0 deletions
diff --git a/lib/lib.c b/lib/lib.c
index 887910fb..8cc85a9f 100644
--- a/lib/lib.c
+++ b/lib/lib.c
@@ -809,3 +809,58 @@ int yesno(int def)
}
return def;
}
+
+// Execute a callback for each PID that matches a process name from a list.
+int for_each_pid_with_name_in(char **names,
+ void (*callback) (const char *pid)) {
+#define PATH_LEN 64
+
+ DIR *dp;
+ struct dirent *entry;
+ FILE *fp;
+ int n, pathpos;
+ char cmd[PATH_MAX];
+ char path[PATH_LEN];
+ char **curname;
+
+ dp = opendir("/proc");
+ if (!dp) {
+ perror("opendir");
+ return 1;
+ }
+
+ while ((entry = readdir(dp))) {
+ if (!isdigit(entry->d_name[0])) continue;
+ strcpy(path, "/proc/");
+ pathpos = 6;
+
+ if (pathpos + strlen(entry->d_name) + 1 > PATH_LEN) continue;
+
+ strcpy(&path[pathpos], entry->d_name);
+ pathpos += strlen(entry->d_name);
+
+ if (pathpos + strlen("/cmdline") + 1 > PATH_LEN) continue;
+ strcpy(&path[pathpos], "/cmdline");
+
+ fp = fopen(path, "r");
+ if (!fp) {
+ perror("fopen");
+ continue;
+ }
+
+ n = fread(cmd, 1, PATH_MAX, fp);
+ fclose(fp);
+ if (n == 0) continue;
+
+ for (curname = names; *curname; curname++) {
+ if (strcmp(basename(cmd), *curname) == 0) {
+ callback(entry->d_name);
+ }
+ }
+ }
+
+ closedir(dp);
+
+ return 0;
+#undef PATH_LEN
+}