pidof: fix -o option being applied without -o flag

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
This commit is contained in:
runitclean 2025-12-17 12:39:17 +01:00 committed by Roberto E. Vargas Caballero
parent a570a80ed1
commit e8249b49ca

18
pidof.c
View File

@ -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;
}