The omit PID list was parsed even when -o was not specified.
In that case, arg was left uninitialized, so passing it to strtok()
resulted in undefined behavior and could lead to a segfault.

Only parse omit PIDs when -o is set.

also fix the exit status to return 1 when no matching PID is found

---
 pidof.c | 18 ++++++++++--------
 1 file changed, 10 insertions(+), 8 deletions(-)

diff --git a/pidof.c b/pidof.c
index c98bf92..355b011 100644
--- a/pidof.c
+++ b/pidof.c
@@ -55,13 +55,15 @@ main(int argc, char *argv[])
 
        SLIST_INIT(&omitpid_head);
 
-       for (p = strtok(arg, ","); p; p = strtok(NULL, ",")) {
-               pe = emalloc(sizeof(*pe));
-               if (strcmp(p, "%PPID") == 0)
-                       pe->pid = getppid();
-               else
-                       pe->pid = estrtol(p, 10);
-               SLIST_INSERT_HEAD(&omitpid_head, pe, entry);
+       if (oflag) {
+               for (p = strtok(arg, ","); p; p = strtok(NULL, ",")) {
+                       pe = emalloc(sizeof(*pe));
+                       if (strcmp(p, "%PPID") == 0)
+                               pe->pid = getppid();
+                       else
+                               pe->pid = estrtol(p, 10);
+                       SLIST_INSERT_HEAD(&omitpid_head, pe, entry);
+               }
        }
 
        if (!(dp = opendir("/proc")))
@@ -110,5 +112,5 @@ out:
 
        closedir(dp);
 
-       return 0;
+       return found ? 0 : 1;
 }
-- 
2.51.0


Reply via email to