ubase

suckless linux base utils
git clone git://git.2f30.org/ubase
Log | Files | Refs | README | LICENSE

commit 6a56bdf4caeb2501487988790b2f611b539be4f3
parent 481d4fefb0cef700034ea5d9e221ea5045f30dd7
Author: sin <sin@2f30.org>
Date:   Thu, 29 Aug 2013 11:11:26 +0100

Add primitive pidof(8)

Diffstat:
MMakefile | 2++
Apidof.c | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mutil.h | 1+
Autil/putword.c | 18++++++++++++++++++
4 files changed, 85 insertions(+), 0 deletions(-)

diff --git a/Makefile b/Makefile @@ -11,6 +11,7 @@ LIB = \ util/estrtol.o \ util/grabmntinfo.o \ util/proc.o \ + util/putword.o \ util/recurse.o \ util/tty.o @@ -27,6 +28,7 @@ SRC = \ mkswap.c \ mount.c \ mountpoint.c \ + pidof.c \ pivot_root.c \ ps.c \ reboot.c \ diff --git a/pidof.c b/pidof.c @@ -0,0 +1,64 @@ +/* See LICENSE file for copyright and license details. */ +#include <sys/types.h> +#include <dirent.h> +#include <libgen.h> +#include <stdio.h> +#include <string.h> +#include "proc.h" +#include "util.h" + +static void +usage(void) +{ + eprintf("usage: %s [program...]\n", argv0); +} + +int +main(int argc, char *argv[]) +{ + DIR *dp; + struct dirent *entry; + pid_t pid; + struct procstat ps; + char cmdline[PATH_MAX], *cmd, *p; + int i, found = 0; + + ARGBEGIN { + default: + usage(); + } ARGEND; + + if (!argc) + return 1; + + if (!(dp = opendir("/proc"))) + eprintf("opendir /proc:"); + + while ((entry = readdir(dp))) { + if (!pidfile(entry->d_name)) + continue; + for (i = 0; i < argc; i++) { + pid = estrtol(entry->d_name, 10); + parsestat(pid, &ps); + if (parsecmdline(ps.pid, cmdline, + sizeof(cmdline)) < 0) { + cmd = ps.comm; + } else { + if ((p = strchr(cmdline, ' '))) + *p = '\0'; + cmd = basename(cmdline); + } + if (strcmp(cmd, argv[i]) == 0) { + putword(entry->d_name); + found++; + } + } + } + + if (found) + putchar('\n'); + + closedir(dp); + + return 0; +} diff --git a/util.h b/util.h @@ -12,5 +12,6 @@ void devtotty(int dev, int *tty_maj, int *tty_min); void enprintf(int, const char *, ...); void eprintf(const char *, ...); long estrtol(const char *, int); +void putword(const char *); void recurse(const char *, void (*)(const char *)); char *ttytostr(int tty_maj, int tty_min); diff --git a/util/putword.c b/util/putword.c @@ -0,0 +1,18 @@ +/* See LICENSE file for copyright and license details. */ +#include <stdbool.h> +#include <stdio.h> + +#include "../util.h" + +void +putword(const char *s) +{ + static bool first = true; + + if(!first) + putchar(' '); + + fputs(s, stdout); + first = false; +} +