Add primitive pidof(8)

This commit is contained in:
sin 2013-08-29 11:11:26 +01:00
parent 481d4fefb0
commit 6a56bdf4ca
4 changed files with 85 additions and 0 deletions

View File

@ -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 \

64
pidof.c Normal file
View File

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

1
util.h
View File

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

18
util/putword.c Normal file
View File

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