aboutsummaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorRob Landley <rob@landley.net>2012-02-18 18:09:14 -0600
committerRob Landley <rob@landley.net>2012-02-18 18:09:14 -0600
commitf42e11b6712f7bd17d1ee2e548f54a2f6d9aed46 (patch)
treef1c0efa3f4f0531ed82a981c5bfff09a7fda304b /lib
parent4797bc28df99576a09f39a6e808d9c8e3f05311f (diff)
downloadtoybox-f42e11b6712f7bd17d1ee2e548f54a2f6d9aed46.tar.gz
Cleanups to pidof (including some global infrastructure shared with killall).
Diffstat (limited to 'lib')
-rw-r--r--lib/lib.c52
1 files changed, 15 insertions, 37 deletions
diff --git a/lib/lib.c b/lib/lib.c
index 8cc85a9f..2c4361a8 100644
--- a/lib/lib.c
+++ b/lib/lib.c
@@ -811,56 +811,34 @@ int yesno(int 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
-
+void for_each_pid_with_name_in(char **names, void (*callback)(pid_t pid))
+{
DIR *dp;
struct dirent *entry;
- FILE *fp;
- int n, pathpos;
- char cmd[PATH_MAX];
- char path[PATH_LEN];
+ char cmd[PATH_MAX], path[64];
char **curname;
- dp = opendir("/proc");
- if (!dp) {
- perror("opendir");
- return 1;
- }
+ if (!(dp = opendir("/proc"))) perror_exit("opendir");
while ((entry = readdir(dp))) {
- if (!isdigit(entry->d_name[0])) continue;
- strcpy(path, "/proc/");
- pathpos = 6;
+ int fd;
- if (pathpos + strlen(entry->d_name) + 1 > PATH_LEN) continue;
+ if (!isdigit(*entry->d_name)) continue;
- strcpy(&path[pathpos], entry->d_name);
- pathpos += strlen(entry->d_name);
+ if (sizeof(path) <= snprintf(path, sizeof(path), "/proc/%s/cmdline",
+ entry->d_name)) continue;
- if (pathpos + strlen("/cmdline") + 1 > PATH_LEN) continue;
- strcpy(&path[pathpos], "/cmdline");
+ if (-1 != (fd=xopen(path, O_RDONLY))) {
+ int n = read(fd, cmd, sizeof(cmd));
- fp = fopen(path, "r");
- if (!fp) {
- perror("fopen");
- continue;
- }
-
- n = fread(cmd, 1, PATH_MAX, fp);
- fclose(fp);
- if (n == 0) continue;
+ close(fd);
+ if (n<1) continue;
- for (curname = names; *curname; curname++) {
- if (strcmp(basename(cmd), *curname) == 0) {
- callback(entry->d_name);
- }
+ for (curname = names; *curname; curname++)
+ if (!strcmp(basename(cmd), *curname))
+ callback(atol(entry->d_name));
}
}
closedir(dp);
-
- return 0;
-#undef PATH_LEN
}