diff 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
line wrap: on
line diff
--- a/lib/pending.c	Thu Sep 05 23:58:35 2013 -0500
+++ b/lib/pending.c	Tue Sep 03 18:43:32 2013 -0500
@@ -6,33 +6,28 @@
 #include "toys.h"
 
 // Execute a callback for each PID that matches a process name from a list.
-void for_each_pid_with_name_in(char **names, int (*callback)(pid_t pid, char *name))
+void name_to_pid(char **names, int (*callback)(pid_t pid, char *name))
 {
   DIR *dp;
   struct dirent *entry;
-  char cmd[sizeof(toybuf)], path[64];
-  char **curname;
 
   if (!(dp = opendir("/proc"))) perror_exit("opendir");
 
   while ((entry = readdir(dp))) {
     int fd, n;
-
-    if (!isdigit(*entry->d_name)) continue;
+    unsigned u;
+    char *cmd, **curname;
 
-    if (sizeof(path) <= snprintf(path, sizeof(path), "/proc/%s/cmdline",
-      entry->d_name)) continue;
-
-    if (-1 == (fd=open(path, O_RDONLY))) continue;
-    n = read(fd, cmd, sizeof(cmd));
-    close(fd);
-    if (n<1) continue;
+    if (!(u = atoi(entry->d_name))) continue;
+    sprintf(libbuf, "/proc/%u/cmdline", u);
+    if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
 
     for (curname = names; *curname; curname++)
-      if (!strcmp(basename(cmd), *curname)) 
-          if (!callback(atol(entry->d_name), *curname)) goto done;
+      if (*curname == '/' ? !strcmp(cmd, *curname)
+          : !strcmp(basename(cmd), basename(*curname))
+        if (!callback(u, *curname)) break;
+    if (*curname) break;
   }
-done:
   closedir(dp);
 }