comparison lib/pending.c @ 1057:242c5de2bb22 draft

Replace for_each_pid_with_name_in_array_perform_callback_function_upon_translated_value() with name_to_pid(), comparing absolute paths or just basename() consistently as spotted by Lukasz Skalski, and adjust callers.
author Rob Landley <rob@landley.net>
date Tue, 03 Sep 2013 18:43:32 -0500
parents f8824260d057
children 4263a4390758
comparison
equal deleted inserted replaced
1056:2b35f9c797ad 1057:242c5de2bb22
4 */ 4 */
5 5
6 #include "toys.h" 6 #include "toys.h"
7 7
8 // Execute a callback for each PID that matches a process name from a list. 8 // Execute a callback for each PID that matches a process name from a list.
9 void for_each_pid_with_name_in(char **names, int (*callback)(pid_t pid, char *name)) 9 void name_to_pid(char **names, int (*callback)(pid_t pid, char *name))
10 { 10 {
11 DIR *dp; 11 DIR *dp;
12 struct dirent *entry; 12 struct dirent *entry;
13 char cmd[sizeof(toybuf)], path[64];
14 char **curname;
15 13
16 if (!(dp = opendir("/proc"))) perror_exit("opendir"); 14 if (!(dp = opendir("/proc"))) perror_exit("opendir");
17 15
18 while ((entry = readdir(dp))) { 16 while ((entry = readdir(dp))) {
19 int fd, n; 17 int fd, n;
18 unsigned u;
19 char *cmd, **curname;
20 20
21 if (!isdigit(*entry->d_name)) continue; 21 if (!(u = atoi(entry->d_name))) continue;
22 22 sprintf(libbuf, "/proc/%u/cmdline", u);
23 if (sizeof(path) <= snprintf(path, sizeof(path), "/proc/%s/cmdline", 23 if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
24 entry->d_name)) continue;
25
26 if (-1 == (fd=open(path, O_RDONLY))) continue;
27 n = read(fd, cmd, sizeof(cmd));
28 close(fd);
29 if (n<1) continue;
30 24
31 for (curname = names; *curname; curname++) 25 for (curname = names; *curname; curname++)
32 if (!strcmp(basename(cmd), *curname)) 26 if (*curname == '/' ? !strcmp(cmd, *curname)
33 if (!callback(atol(entry->d_name), *curname)) goto done; 27 : !strcmp(basename(cmd), basename(*curname))
28 if (!callback(u, *curname)) break;
29 if (*curname) break;
34 } 30 }
35 done:
36 closedir(dp); 31 closedir(dp);
37 } 32 }
38 33
39 /* 34 /*
40 * used to get the interger value. 35 * used to get the interger value.