commit 23456faa5135fe30fe440ce22e081936f94d7a59
parent a2a35997b87104611c1a520d89718983f0da98c6
Author: xplshn <anto@xplshn.com.ar>
Date: Mon, 23 Nov 2026 21:23:21 -0300
ps: the options POSIX has and -o, over a process table with a backend per kernel. pkill, as pgrep that sends a signal
Diffstat:
8 files changed, 859 insertions(+), 323 deletions(-)
diff --git a/cmd/extra/pgrep.c b/cmd/extra/pgrep.c
@@ -1,11 +1,13 @@
/* see LICENSE file for copyright and license details */
#include <sys/types.h>
+#include <ctype.h>
#include <errno.h>
#include <libgen.h>
#include <limits.h>
#include <pwd.h>
#include <regex.h>
+#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -13,6 +15,7 @@
#include "paths.h"
#include "proc.h"
+#include "sig.h"
#include "util.h"
enum {
@@ -29,6 +32,10 @@ struct hit {
unsigned long long starttime;
};
+/* pkill is pgrep that sends a signal to what it finds instead of listing it:
+ * the one program, as grep is egrep and fgrep, so what is a match is written
+ * once */
+static int killing, signo = SIGTERM;
static int flags;
static regex_t preg;
static uid_t user_uid;
@@ -76,6 +83,11 @@ show(pid_t pid, const char *comm)
char cmdline[BUFSIZ];
count++;
+ if (killing) {
+ if (kill(pid, signo) < 0)
+ weprintf("kill %d:", pid);
+ return;
+ }
if (flags & PGREP_cflag)
return;
if (flags & PGREP_aflag) {
@@ -90,67 +102,59 @@ show(pid_t pid, const char *comm)
}
}
-static void
-pgrepr(const char *file)
+static int
+pgrepr(const struct procinfo *p, void *arg)
{
- char path[PATH_MAX], *p;
- struct procstat ps;
- struct procstatus pstatus;
- char cmdline[BUFSIZ];
- const char *target;
- pid_t pid;
- int matched;
-
- if (strlcpy(path, file, sizeof(path)) >= sizeof(path))
- eprintf("path too long\n");
- p = basename(path);
- if (pidfile(p) == 0)
- return;
- pid = estrtol(p, 10);
- if (pid == self)
- return;
- if (parsestat(pid, &ps) < 0)
- return;
-
- if (have_user) {
- if (parsestatus(pid, &pstatus) < 0)
- return;
- if (pstatus.euid != user_uid)
- return;
- }
+ struct procstat ps;
+ char cmdline[BUFSIZ];
+ const char *target = p->comm;
+ int matched;
- if (flags & PGREP_fflag) {
- if (parsecmdline(pid, cmdline, sizeof(cmdline)) < 0)
- target = ps.comm;
- else
- target = cmdline;
- } else {
- target = ps.comm;
- }
+ (void)arg;
+ if (p->pid == self)
+ return 0;
+ if (have_user && p->euid != user_uid)
+ return 0;
+ if ((flags & PGREP_fflag) && proc_args(p->pid, cmdline, sizeof(cmdline)) == 0)
+ target = cmdline;
matched = matches(target);
if (flags & PGREP_vflag)
matched = !matched;
if (!matched)
- return;
+ return 0;
+ ps.starttime = (unsigned long long)p->start;
if (select_mode != PGREP_NONE)
- record(pid, ps.starttime);
+ record(p->pid, ps.starttime);
else
- show(pid, ps.comm);
+ show(p->pid, p->comm);
+ return 0;
}
static void
usage(void)
{
+ if (killing)
+ eprintf("usage: %s [-signal] [-fxv] [-u user] [-n | -o] pattern\n", argv0);
eprintf("usage: %s [-flaxvc] [-u user] [-n | -o] pattern\n", argv0);
}
+/* what the program was started as, without its directory */
+static int
+invoked_as(const char *name)
+{
+ const char *base = strrchr(argv0, '/');
+
+ return strcmp(base ? base + 1 : argv0, name) == 0;
+}
+
// ?man pgrep: list processes by name
// ?man arguments: pattern
// ?man pgrep matches pattern, a POSIX extended regular expression,
// ?man against each running process's name (or full command line
-// ?man with -f) and prints the pid of every match, one per line
+// ?man with -f) and prints the pid of every match, one per line. run as
+// ?man pkill it sends them a signal instead, TERM unless -signal names one
int
main(int argc, char *argv[])
{
@@ -160,6 +164,21 @@ main(int argc, char *argv[])
const char *user = NULL;
size_t i, pick;
+ argv0 = argv[0];
+ if (invoked_as("pkill")) {
+ killing = 1;
+ // a leading -TERM or -9 is the signal, as kill takes it
+ if (argc > 1 && argv[1][0] == '-' && argv[1][1] && (isdigit((unsigned char)argv[1][1]) || isupper((unsigned char)argv[1][1]))) {
+ if (isdigit((unsigned char)argv[1][1]))
+ signo = (int)estrtonum(argv[1] + 1, 0, INT_MAX);
+ else if (str2sig(argv[1] + 1, &signo) < 0)
+ eprintf("%s: bad signal name\n", argv[1] + 1);
+ argc--;
+ argv++;
+ argv[0] = argv[-1];
+ }
+ }
+
ARGBEGIN
{
// ?man -f: match the full command line instead of just the name
@@ -222,7 +241,8 @@ main(int argc, char *argv[])
eregcomp(&preg, argv[0], REG_EXTENDED);
self = getpid();
- recurse_dir(ARUU_LINUX_PATH_PROC, pgrepr);
+ if (proc_each(pgrepr, NULL) < 0)
+ eprintf("the process table cannot be read:");
if (select_mode != PGREP_NONE && nhits > 0) {
pick = 0;
diff --git a/cmd/posix/ps.c b/cmd/posix/ps.c
@@ -1,10 +1,9 @@
/* see LICENSE file for copyright and license details */
-
#include <sys/ioctl.h>
-#include <sys/sysinfo.h>
+#include <sys/types.h>
-#include <errno.h>
-#include <libgen.h>
+#include <ctype.h>
+#include <grp.h>
#include <limits.h>
#include <pwd.h>
#include <stdio.h>
@@ -16,187 +15,466 @@
#include "proc.h"
#include "util.h"
-static void psout(struct procstat *ps);
-static void psr(const char *file);
+/* what -o can name, and what each is headed with. a column says how to write
+ * one process into text, so the default, -f, -l and -o all print the same
+ * way */
+struct column {
+ const char *name, *head;
+ int width; /* negative: left aligned */
+ void (*put)(const struct procinfo *p, char *out, size_t n);
+};
-enum { PS_aflag = 1 << 0, PS_Aflag = 1 << 1, PS_dflag = 1 << 2, PS_fflag = 1 << 3 };
+enum { PS_A = 1 << 0, PS_a = 1 << 1, PS_d = 1 << 2, PS_f = 1 << 3, PS_l = 1 << 4 };
static int flags;
+/* the lists -p -t -u -U -g -G take: comma or space separated words */
+struct list {
+ char **w;
+ int n;
+};
+
+static struct list pids, ttys, users, ruser, sids, rgroups;
+static char *headers[32];
+static const struct column *chosen[32];
+static int nchosen;
+static int allheadless; /* every -o column had its own header text, empty */
+
+static void
+username(uid_t uid, char *out, size_t n)
+{
+ struct passwd *pw = getpwuid(uid);
+
+ if (pw)
+ snprintf(out, n, "%s", pw->pw_name);
+ else
+ snprintf(out, n, "%u", (unsigned)uid);
+}
+
+static void
+groupname(gid_t gid, char *out, size_t n)
+{
+ struct group *gr = getgrgid(gid);
+
+ if (gr)
+ snprintf(out, n, "%s", gr->gr_name);
+ else
+ snprintf(out, n, "%u", (unsigned)gid);
+}
+
+static void
+hms(unsigned long secs, char *out, size_t n)
+{
+ snprintf(out, n, "%02lu:%02lu:%02lu", secs / 3600, (secs % 3600) / 60, secs % 60);
+}
+
+static void put_user(const struct procinfo *p, char *o, size_t n) { username(p->euid, o, n); }
+static void put_ruser(const struct procinfo *p, char *o, size_t n) { username(p->ruid, o, n); }
+static void put_group(const struct procinfo *p, char *o, size_t n) { groupname(p->egid, o, n); }
+static void put_rgroup(const struct procinfo *p, char *o, size_t n) { groupname(p->rgid, o, n); }
+static void put_uid(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%u", (unsigned)p->euid); }
+static void put_pid(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%d", (int)p->pid); }
+static void put_ppid(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%d", (int)p->ppid); }
+static void put_pgid(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%d", (int)p->pgid); }
+static void put_nice(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%ld", p->nice); }
+static void put_pri(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%ld", p->priority); }
+static void put_vsz(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%lu", p->vsize_kib); }
+static void put_sz(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%lu", p->vsize_kib / 4); }
+static void put_state(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%c", p->state); }
+static void put_time(const struct procinfo *p, char *o, size_t n) { hms(p->cpu, o, n); }
+static void put_comm(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%s", p->comm); }
+static void put_zero(const struct procinfo *p, char *o, size_t n) { (void)p; snprintf(o, n, "0"); }
+static void put_dash(const struct procinfo *p, char *o, size_t n) { (void)p; snprintf(o, n, "-"); }
+
static void
-psout(struct procstat *ps)
-{
- struct procstatus pstatus;
- char cmdline[BUFSIZ], *cmd;
- char buf[sizeof(cmdline) + sizeof(ps->comm) + 1024];
- char ttystr[TTY_NAME_MAX], *myttystr;
- int tty_maj, tty_min;
- uid_t myeuid;
- unsigned sutime;
- time_t start;
- char stimestr[sizeof("%H:%M")];
- struct sysinfo info;
- struct passwd *pw;
- struct winsize w;
-
- /* ignore session leaders */
- if (flags & PS_dflag)
- if (ps->pid == ps->sid)
- return;
-
- devtotty(ps->tty_nr, &tty_maj, &tty_min);
- ttytostr(tty_maj, tty_min, ttystr, sizeof(ttystr));
-
- /* only print processes that are associated with
- * a terminal and they are not session leaders */
- if (flags & PS_aflag)
- if (ps->pid == ps->sid || ttystr[0] == '?')
- return;
-
- if (parsestatus(ps->pid, &pstatus) < 0)
+put_tty(const struct procinfo *p, char *o, size_t n)
+{
+ proc_ttyname(p->tty_major, p->tty_minor, o, n);
+}
+
+/* the command line, or the name in brackets for what has none, as a kernel
+ * thread */
+static void
+put_args(const struct procinfo *p, char *o, size_t n)
+{
+ char args[BUFSIZ];
+
+ size_t len;
+
+ if (proc_args(p->pid, args, sizeof args) < 0) {
+ snprintf(o, n, "[%s]", p->comm);
return;
+ }
+ /* the words end with the nul that ended the last, made a space */
+ for (len = strlen(args); len && args[len - 1] == ' '; len--)
+ args[len - 1] = '\0';
+ snprintf(o, n, "%s", args);
+}
+
+/* the program's name, and with -f its command line: what CMD says */
+static void
+put_cmd(const struct procinfo *p, char *o, size_t n)
+{
+ if (flags & PS_f)
+ put_args(p, o, n);
+ else
+ put_comm(p, o, n);
+}
- /* this is the default case, only print processes that have
- * the same controlling terminal as the invoker and the same
- * euid as the current user */
- if (!(flags & (PS_aflag | PS_Aflag | PS_dflag))) {
- myttystr = ttyname(0);
- if (myttystr) {
- if (strcmp(myttystr + strlen("/dev/"), ttystr))
- return;
+/* how long it has run: [[dd-]hh:]mm:ss */
+static void
+put_etime(const struct procinfo *p, char *o, size_t n)
+{
+ unsigned long s = time(NULL) > p->start ? (unsigned long)(time(NULL) - p->start) : 0;
+
+ if (s >= 86400)
+ snprintf(o, n, "%lu-%02lu:%02lu:%02lu", s / 86400, (s % 86400) / 3600, (s % 3600) / 60, s % 60);
+ else if (s >= 3600)
+ snprintf(o, n, "%02lu:%02lu:%02lu", s / 3600, (s % 3600) / 60, s % 60);
+ else
+ snprintf(o, n, "%02lu:%02lu", s / 60, s % 60);
+}
+
+/* when it began: the time of day, or the day when it was before today */
+static void
+put_stime(const struct procinfo *p, char *o, size_t n)
+{
+ struct tm tm, now;
+ time_t t = time(NULL);
+
+ localtime_r(&p->start, &tm);
+ localtime_r(&t, &now);
+ if (tm.tm_yday == now.tm_yday && tm.tm_year == now.tm_year)
+ strftime(o, n, "%H:%M", &tm);
+ else
+ strftime(o, n, "%b%d", &tm);
+}
+
+/* the share of the time it has been there that it spent running */
+static void
+put_pcpu(const struct procinfo *p, char *o, size_t n)
+{
+ time_t life = time(NULL) - p->start;
+
+ snprintf(o, n, "%.1f", life > 0 ? 100.0 * (double)p->cpu / (double)life : 0.0);
+}
+
+static const struct column columns[] = {
+ {"user", "USER", -8, put_user}, {"ruser", "RUSER", -8, put_ruser},
+ {"group", "GROUP", -8, put_group}, {"rgroup", "RGROUP", -8, put_rgroup},
+ {"uid", "UID", -8, put_user}, {"pid", "PID", 5, put_pid},
+ {"ppid", "PPID", 5, put_ppid}, {"pgid", "PGID", 5, put_pgid},
+ {"etime", "ELAPSED", 11, put_etime},{"nice", "NI", 3, put_nice},
+ {"pcpu", "%CPU", 4, put_pcpu}, {"vsz", "VSZ", 7, put_vsz},
+ {"time", "TIME", 8, put_time}, {"tty", "TT", -8, put_tty},
+ {"comm", "COMMAND", -15, put_comm}, {"args", "COMMAND", -15, put_args},
+ /* the names of -f and -l, which are not the ones of -o */
+ {"f", "F", 1, put_zero}, {"s", "S", 1, put_state},
+ {"c", "C", 2, put_zero}, {"pri", "PRI", 3, put_pri},
+ {"addr", "ADDR", 4, put_dash}, {"sz", "SZ", 6, put_sz},
+ {"wchan", "WCHAN", 6, put_dash}, {"stime", "STIME", 5, put_stime},
+ {"cmd", "CMD", -15, put_cmd},
+};
+
+static const struct column *
+column(const char *name)
+{
+ size_t i;
+
+ for (i = 0; i < sizeof columns / sizeof *columns; i++)
+ if (!strcmp(columns[i].name, name))
+ return &columns[i];
+ return NULL;
+}
+
+static void
+choose(const char *name, const char *head)
+{
+ const struct column *c = column(name);
+
+ if (!c)
+ eprintf("%s: unknown format keyword\n", name);
+ if (nchosen == 32)
+ eprintf("too many columns\n");
+ headers[nchosen] = (char *)(head ? head : c->head);
+ chosen[nchosen++] = c;
+}
+
+/* -o's list: keywords, each with its own header after an =. a list whose
+ * every header is empty prints no header line */
+static void
+add_format(char *arg)
+{
+ char *tok, *eq;
+
+ for (tok = strtok(arg, ", "); tok; tok = strtok(NULL, ", ")) {
+ eq = strchr(tok, '=');
+ if (eq) {
+ *eq = '\0';
+ choose(tok, eq + 1);
+ if (*(eq + 1) == '\0')
+ allheadless++;
} else {
- /* the invoker has no controlling terminal - just
- * go ahead and print the processes anyway */
- ttystr[0] = '?';
- ttystr[1] = '\0';
+ choose(tok, NULL);
}
- myeuid = geteuid();
- if (myeuid != pstatus.euid)
- return;
}
+}
- sutime = (ps->stime + ps->utime) / sysconf(_SC_CLK_TCK);
-
- ioctl(1, TIOCGWINSZ, &w);
- if (!(flags & PS_fflag)) {
- snprintf(
- buf,
- sizeof(buf),
- "%5d %-6s %02u:%02u:%02u %s",
- ps->pid,
- ttystr,
- sutime / 3600,
- (sutime % 3600) / 60,
- sutime % 60,
- ps->comm
- );
- if (w.ws_col)
- printf("%.*s\n", w.ws_col, buf);
- else
- printf("%s\n", buf);
- } else {
- errno = 0;
- pw = getpwuid(pstatus.uid);
- if (!pw)
- eprintf("getpwuid %d:", pstatus.uid);
-
- if (sysinfo(&info) < 0)
- eprintf("sysinfo:");
-
- start = time(NULL) - info.uptime;
- start += (ps->starttime / sysconf(_SC_CLK_TCK));
- strftime(stimestr, sizeof(stimestr), "%H:%M", localtime(&start));
-
- /* for kthreads/zombies /proc/<pid>/cmdline will be
- * empty so use ps->comm in that case */
- if (parsecmdline(ps->pid, cmdline, sizeof(cmdline)) < 0)
- cmd = ps->comm;
- else
- cmd = cmdline;
-
- snprintf(
- buf,
- sizeof(buf),
- "%-8s %5d %5d ? %5s %-5s %02u:%02u:%02u %s%s%s",
- pw->pw_name,
- ps->pid,
- ps->ppid,
- stimestr,
- ttystr,
- sutime / 3600,
- (sutime % 3600) / 60,
- sutime % 60,
- (cmd == ps->comm) ? "[" : "",
- cmd,
- (cmd == ps->comm) ? "]" : ""
- );
- if (w.ws_col)
- printf("%.*s\n", w.ws_col, buf);
- else
- printf("%s\n", buf);
+static void
+add_list(struct list *l, char *arg)
+{
+ char *tok;
+
+ for (tok = strtok(arg, ", "); tok; tok = strtok(NULL, ", ")) {
+ l->w = ereallocarray(l->w, l->n + 1, sizeof(*l->w));
+ l->w[l->n++] = tok;
}
}
-static void
-psr(const char *file)
+static int
+in_list(const struct list *l, const char *s)
{
- char path[PATH_MAX], *p;
- struct procstat ps;
- pid_t pid;
+ int i;
- if (strlcpy(path, file, sizeof(path)) >= sizeof(path))
- eprintf("path too long\n");
- p = basename(path);
- if (pidfile(p) == 0)
- return;
- pid = estrtol(p, 10);
- if (parsestat(pid, &ps) < 0)
- return;
- psout(&ps);
+ for (i = 0; i < l->n; i++)
+ if (!strcmp(l->w[i], s))
+ return 1;
+ return 0;
+}
+
+static int
+user_in(const struct list *l, uid_t uid)
+{
+ char name[64], num[16];
+
+ username(uid, name, sizeof name);
+ snprintf(num, sizeof num, "%u", (unsigned)uid);
+ return in_list(l, name) || in_list(l, num);
+}
+
+static int
+group_in(const struct list *l, gid_t gid)
+{
+ char name[64], num[16];
+
+ groupname(gid, name, sizeof name);
+ snprintf(num, sizeof num, "%u", (unsigned)gid);
+ return in_list(l, name) || in_list(l, num);
+}
+
+/* a terminal as -t names it: pts/3, or tty1, or the same without the dir */
+static int
+tty_in(const struct list *l, const struct procinfo *p)
+{
+ char name[32];
+
+ proc_ttyname(p->tty_major, p->tty_minor, name, sizeof name);
+ return in_list(l, name) || (!strncmp(name, "pts/", 4) && in_list(l, name + 4));
+}
+
+static char mytty[32];
+static uid_t myuid;
+static int have_tty;
+
+/* whether a process is one of those asked for */
+static int
+wanted(const struct procinfo *p)
+{
+ char num[16];
+ int selected = 0, listed = 0;
+
+ snprintf(num, sizeof num, "%d", (int)p->pid);
+ if (pids.n) { listed = 1; selected |= in_list(&pids, num); }
+ if (ttys.n) { listed = 1; selected |= tty_in(&ttys, p); }
+ if (users.n) { listed = 1; selected |= user_in(&users, p->euid); }
+ if (ruser.n) { listed = 1; selected |= user_in(&ruser, p->ruid); }
+ if (rgroups.n) { listed = 1; selected |= group_in(&rgroups, p->rgid); }
+ if (sids.n) { listed = 1; selected |= in_list(&sids, (snprintf(num, sizeof num, "%d", (int)p->sid), num)); }
+ if (flags & PS_A)
+ return 1;
+ if (flags & PS_a) {
+ if (p->pid != p->sid && (p->tty_major || p->tty_minor))
+ return 1;
+ return selected;
+ }
+ if (flags & PS_d) {
+ if (p->pid != p->sid)
+ return 1;
+ return selected;
+ }
+ if (listed)
+ return selected;
+ /* nothing asked for: the invoker's, on the invoker's terminal */
+ if (p->euid != myuid)
+ return 0;
+ if (have_tty) {
+ char name[32];
+
+ proc_ttyname(p->tty_major, p->tty_minor, name, sizeof name);
+ return !strcmp(name, mytty);
+ }
+ return 1;
+}
+
+static int width;
+
+static int
+show(const struct procinfo *p, void *arg)
+{
+ char line[BUFSIZ * 2], cell[BUFSIZ];
+ size_t at = 0;
+ int i;
+
+ (void)arg;
+ if (!wanted(p))
+ return 0;
+ for (i = 0; i < nchosen; i++) {
+ chosen[i]->put(p, cell, sizeof cell);
+ /* the last column runs as long as it is */
+ if (i == nchosen - 1)
+ at += (size_t)snprintf(line + at, sizeof line - at, "%s%s", i ? " " : "", cell);
+ else
+ at += (size_t)snprintf(line + at, sizeof line - at, "%s%*s", i ? " " : "", chosen[i]->width, cell);
+ if (at >= sizeof line)
+ at = sizeof line - 1;
+ }
+ if (width && at > (size_t)width)
+ line[width] = '\0';
+ puts(line);
+ return 0;
}
static void
usage(void)
{
- eprintf("usage: %s [-aAdef]\n", argv0);
+ eprintf(
+ "usage: %s [-aAdefl] [-g grouplist] [-G grouplist] [-o format]... [-p proclist]\n"
+ " [-t termlist] [-u userlist] [-U userlist]\n",
+ argv0
+ );
}
// ?man ps: report process status
-// ?man display information about active system processes
+// ?man ps writes information about processes: by default those of the
+// ?man invoker on the terminal it was run from. the processes of every
+// ?man kernel it has a process table backend for are written the same
int
main(int argc, char *argv[])
{
+ char *name;
+ int i;
+ struct winsize w = {0};
+
ARGBEGIN
{
- // ?man -a: print or show all entries
- case 'a':
- flags |= PS_aflag;
- break;
- // ?man -A: specify option flag
+ // ?man -A: every process
case 'A':
- flags |= PS_Aflag;
+ flags |= PS_A;
break;
- // ?man -d: specify directory
- case 'd':
- flags |= PS_dflag;
- break;
- // ?man -e: specify expression or pattern
+ // ?man -e: every process, as -A
case 'e':
- flags |= PS_Aflag;
+ flags |= PS_A;
+ break;
+ // ?man -a: the processes with a terminal that are not session leaders
+ case 'a':
+ flags |= PS_a;
break;
- // ?man -f: force the operation
+ // ?man -d: every process but the session leaders
+ case 'd':
+ flags |= PS_d;
+ break;
+ // ?man -f: a full listing, with the owner, the parent and the start
case 'f':
- flags |= PS_fflag;
+ flags |= PS_f;
+ break;
+ // ?man -l: a long listing
+ case 'l':
+ flags |= PS_l;
+ break;
+ // ?man -n: accepted and ignored, the name list of the system is not used
+ case 'n':
+ (void)EARGF(usage());
+ break;
+ // ?man -o:format: the columns written, keywords with an optional =header
+ case 'o':
+ add_format(EARGF(usage()));
+ break;
+ // ?man -p:proclist: only these processes
+ case 'p':
+ add_list(&pids, EARGF(usage()));
+ break;
+ // ?man -t:termlist: only the processes on these terminals
+ case 't':
+ add_list(&ttys, EARGF(usage()));
+ break;
+ // ?man -u:userlist: only the processes of these effective users
+ case 'u':
+ add_list(&users, EARGF(usage()));
+ break;
+ // ?man -U:userlist: only the processes of these real users
+ case 'U':
+ add_list(&ruser, EARGF(usage()));
+ break;
+ // ?man -g:sidlist: only the processes of these sessions
+ case 'g':
+ add_list(&sids, EARGF(usage()));
+ break;
+ // ?man -G:grouplist: only the processes of these real groups
+ case 'G':
+ add_list(&rgroups, EARGF(usage()));
break;
default:
usage();
}
ARGEND;
- if (!(flags & PS_fflag))
- printf(" PID TTY TIME CMD\n");
- else
- printf("UID PID PPID C STIME TTY TIME CMD\n");
- recurse_dir("/proc", psr);
- return 0;
+ if (argc)
+ usage();
+
+ /* the default, -f and -l are named lists of columns */
+ if (!nchosen) {
+ const char *set[] = {"pid", "tty", "time", "cmd"};
+ const char *full[] = {"uid", "pid", "ppid", "c", "stime", "tty", "time", "cmd"};
+ const char *lng[] = {"f", "s", "uid", "pid", "ppid", "c", "pri", "nice", "addr", "sz", "wchan", "tty", "time", "cmd"};
+ const char **l = (flags & PS_l) ? lng : (flags & PS_f) ? full : set;
+ size_t k, n = (flags & PS_l) ? sizeof lng / sizeof *lng : (flags & PS_f) ? sizeof full / sizeof *full : sizeof set / sizeof *set;
+
+ for (k = 0; k < n; k++)
+ choose(l[k], NULL);
+ }
+
+ if ((name = ttyname(0))) {
+ unsigned maj = 0, min = 0;
+ struct procinfo me;
+
+ if (proc_info(getpid(), &me) == 0) {
+ maj = me.tty_major;
+ min = me.tty_minor;
+ }
+ proc_ttyname(maj, min, mytty, sizeof mytty);
+ have_tty = mytty[0] != '?' || mytty[1];
+ (void)name;
+ }
+ myuid = geteuid();
+ if (ioctl(1, TIOCGWINSZ, &w) == 0)
+ width = w.ws_col;
+
+ /* a header line, unless every column was given an empty header */
+ if (allheadless < nchosen) {
+ char head[BUFSIZ];
+ size_t at = 0;
+
+ for (i = 0; i < nchosen; i++) {
+ if (i == nchosen - 1)
+ at += (size_t)snprintf(head + at, sizeof head - at, "%s%s", i ? " " : "", headers[i]);
+ else
+ at += (size_t)snprintf(head + at, sizeof head - at, "%s%*s", i ? " " : "", chosen[i]->width, headers[i]);
+ if (at >= sizeof head)
+ at = sizeof head - 1;
+ }
+ puts(head);
+ }
+ if (proc_each(show, NULL) < 0)
+ eprintf("the process table cannot be read:");
+ return fshut(stdout, "<stdout>");
}
diff --git a/ninqu.rules b/ninqu.rules
@@ -42,6 +42,7 @@
(glob "shared/libutil/*.c")
(skip "filesystem_linux.c" "filesystem_other.c"
"net_linux.c" "net_other.c"
+ "proc_linux.c" "proc_other.c"
"sysinfo_linux.c" "sysinfo_other.c")
(dep $(MATCH) FEATURES_H)
(after NOFORK_LIST_H)
@@ -53,9 +54,11 @@
"shared/libutil/filesystem_other.c"
"shared/libutil/net_linux.c"
"shared/libutil/net_other.c"
+ "shared/libutil/proc_linux.c"
+ "shared/libutil/proc_other.c"
"shared/libutil/sysinfo_linux.c"
"shared/libutil/sysinfo_other.c")
- (dep $(MATCH) "shared/filesystem.h" "shared/net.h"
+ (dep $(MATCH) "shared/filesystem.h" "shared/net.h" "shared/proc.h"
"shared/sysinfo.h" FEATURES_H)
(after NOFORK_LIST_H)
(out "shared/libutil/$(BASESTEM).o")
diff --git a/scripts/genbox.sh b/scripts/genbox.sh
@@ -75,6 +75,9 @@ for category in $categories; do
if [ "$tool" = "test" ]; then
printf '\t{ "[", %s, "%s" },\n' "$sym" "$category"
fi
+ if [ "$tool" = "pgrep" ]; then
+ printf '\t{ "pkill", %s, "%s" },\n' "$sym" "$category"
+ fi
if [ "$tool" = "grep" ]; then
printf '\t{ "egrep", %s, "%s" },\n' "$sym" "$category"
printf '\t{ "fgrep", %s, "%s" },\n' "$sym" "$category"
diff --git a/shared/libutil/proc.c b/shared/libutil/proc.c
@@ -1,135 +0,0 @@
-/* see LICENSE file for copyright and license details */
-#include <sys/stat.h>
-
-#include <errno.h>
-#include <fcntl.h>
-#include <limits.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "../paths.h"
-#include "../proc.h"
-#include "../util.h"
-
-int
-parsecmdline(pid_t pid, char *buf, size_t siz)
-{
- int fd;
- char path[PATH_MAX];
- ssize_t n, i;
-
- snprintf(path, sizeof(path), ARUU_LINUX_PATH_PROC "/%ld/cmdline", (long)pid);
- fd = open(path, O_RDONLY);
- if (fd < 0)
- return -1;
- n = read(fd, buf, siz > 0 ? siz - 1 : 0);
- close(fd);
- if (n <= 0)
- return -1;
- buf[n] = '\0';
- for (i = 0; i < n; i++)
- if (buf[i] == '\0')
- buf[i] = ' ';
- return 0;
-}
-
-int
-parsestat(pid_t pid, struct procstat *ps)
-{
- char path[PATH_MAX], line[BUFSIZ], *lp, *rp;
- FILE *fp;
- size_t len;
- int n;
-
- snprintf(path, sizeof(path), ARUU_LINUX_PATH_PROC "/%d/stat", pid);
- if (!(fp = fopen(path, "r")))
- return -1;
- n = fgets(line, sizeof(line), fp) != NULL;
- fclose(fp);
- /* comm is whatever the process named itself, spaces and parens included,
- * so it runs from the first ( to the last ) */
- if (!n || !(lp = strchr(line, '(')) || !(rp = strrchr(line, ')')) || rp < lp) {
- errno = EINVAL;
- return -1;
- }
- len = MIN((size_t)(rp - lp - 1), sizeof(ps->comm) - 1);
- memcpy(ps->comm, lp + 1, len);
- ps->comm[len] = '\0';
- ps->pid = pid;
- n = sscanf(
- rp + 1,
- " %c %d %d %d %d %d %u %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld %llu %lu %ld %lu",
- &ps->state,
- &ps->ppid,
- &ps->pgrp,
- &ps->sid,
- &ps->tty_nr,
- &ps->tpgid,
- &ps->flags,
- &ps->minflt,
- &ps->cminflt,
- &ps->majflt,
- &ps->cmajflt,
- &ps->utime,
- &ps->stime,
- &ps->cutime,
- &ps->cstime,
- &ps->priority,
- &ps->nice,
- &ps->num_threads,
- &ps->itrealvalue,
- &ps->starttime,
- &ps->vsize,
- &ps->rss,
- &ps->rsslim
- );
- if (n != 23) {
- errno = EINVAL;
- return -1;
- }
- return 0;
-}
-
-int
-parsestatus(pid_t pid, struct procstatus *pstatus)
-{
- char path[PATH_MAX];
- char buf[BUFSIZ], *off;
- int fd;
- ssize_t n;
-
- snprintf(path, sizeof(path), ARUU_LINUX_PATH_PROC "/%d/status", pid);
- fd = open(path, O_RDONLY);
- if (fd < 0)
- return -1;
- n = read(fd, buf, sizeof(buf) - 1);
- close(fd);
- if (n <= 0)
- return -1;
- buf[n] = '\0';
- off = strstr(buf, "Uid:");
- if (!off)
- return -1;
- sscanf(off, "Uid: %u %u", &pstatus->uid, &pstatus->euid);
- off = strstr(buf, "Gid:");
- if (!off)
- return -1;
- sscanf(off, "Gid: %u %u", &pstatus->gid, &pstatus->egid);
- return 0;
-}
-
-int
-pidfile(const char *file)
-{
- char *end;
-
- errno = 0;
- strtol(file, &end, 10);
- if (*end != '\0')
- return 0;
- if (errno != 0)
- return 0;
- return 1;
-}
diff --git a/shared/libutil/proc_linux.c b/shared/libutil/proc_linux.c
@@ -0,0 +1,254 @@
+/* see LICENSE file for copyright and license details */
+#include <sys/stat.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "../paths.h"
+#include "../proc.h"
+#include "../util.h"
+
+#include <dirent.h>
+#include <time.h>
+
+#if defined(__linux__) && !defined(ARUU_FORCE_OTHER)
+
+int
+parsecmdline(pid_t pid, char *buf, size_t siz)
+{
+ int fd;
+ char path[PATH_MAX];
+ ssize_t n, i;
+
+ snprintf(path, sizeof(path), ARUU_LINUX_PATH_PROC "/%ld/cmdline", (long)pid);
+ fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return -1;
+ n = read(fd, buf, siz > 0 ? siz - 1 : 0);
+ close(fd);
+ if (n <= 0)
+ return -1;
+ buf[n] = '\0';
+ for (i = 0; i < n; i++)
+ if (buf[i] == '\0')
+ buf[i] = ' ';
+ return 0;
+}
+
+int
+parsestat(pid_t pid, struct procstat *ps)
+{
+ char path[PATH_MAX], line[BUFSIZ], *lp, *rp;
+ FILE *fp;
+ size_t len;
+ int n;
+
+ snprintf(path, sizeof(path), ARUU_LINUX_PATH_PROC "/%d/stat", pid);
+ if (!(fp = fopen(path, "r")))
+ return -1;
+ n = fgets(line, sizeof(line), fp) != NULL;
+ fclose(fp);
+ /* comm is whatever the process named itself, spaces and parens included,
+ * so it runs from the first ( to the last ) */
+ if (!n || !(lp = strchr(line, '(')) || !(rp = strrchr(line, ')')) || rp < lp) {
+ errno = EINVAL;
+ return -1;
+ }
+ len = MIN((size_t)(rp - lp - 1), sizeof(ps->comm) - 1);
+ memcpy(ps->comm, lp + 1, len);
+ ps->comm[len] = '\0';
+ ps->pid = pid;
+ n = sscanf(
+ rp + 1,
+ " %c %d %d %d %d %d %u %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld %llu %lu %ld %lu",
+ &ps->state,
+ &ps->ppid,
+ &ps->pgrp,
+ &ps->sid,
+ &ps->tty_nr,
+ &ps->tpgid,
+ &ps->flags,
+ &ps->minflt,
+ &ps->cminflt,
+ &ps->majflt,
+ &ps->cmajflt,
+ &ps->utime,
+ &ps->stime,
+ &ps->cutime,
+ &ps->cstime,
+ &ps->priority,
+ &ps->nice,
+ &ps->num_threads,
+ &ps->itrealvalue,
+ &ps->starttime,
+ &ps->vsize,
+ &ps->rss,
+ &ps->rsslim
+ );
+ if (n != 23) {
+ errno = EINVAL;
+ return -1;
+ }
+ return 0;
+}
+
+int
+parsestatus(pid_t pid, struct procstatus *pstatus)
+{
+ char path[PATH_MAX];
+ char buf[BUFSIZ], *off;
+ int fd;
+ ssize_t n;
+
+ snprintf(path, sizeof(path), ARUU_LINUX_PATH_PROC "/%d/status", pid);
+ fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return -1;
+ n = read(fd, buf, sizeof(buf) - 1);
+ close(fd);
+ if (n <= 0)
+ return -1;
+ buf[n] = '\0';
+ off = strstr(buf, "Uid:");
+ if (!off)
+ return -1;
+ sscanf(off, "Uid: %u %u", &pstatus->uid, &pstatus->euid);
+ off = strstr(buf, "Gid:");
+ if (!off)
+ return -1;
+ sscanf(off, "Gid: %u %u", &pstatus->gid, &pstatus->egid);
+ return 0;
+}
+
+int
+pidfile(const char *file)
+{
+ char *end;
+
+ errno = 0;
+ strtol(file, &end, 10);
+ if (*end != '\0')
+ return 0;
+ if (errno != 0)
+ return 0;
+ return 1;
+}
+
+/* the terminal of a process as stat gives it: a device number in the
+ * kernel's own encoding */
+static void
+tty_split(int nr, unsigned *major, unsigned *minor)
+{
+ unsigned dev = (unsigned)nr;
+
+ *major = (dev & 0xfff00) >> 8;
+ *minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
+}
+
+/* when the system started, seconds since the epoch, from stat's btime */
+static time_t
+boot_time(void)
+{
+ static time_t boot;
+ char line[256];
+ FILE *fp;
+
+ if (boot)
+ return boot;
+ if ((fp = fopen(ARUU_LINUX_PATH_PROC "/stat", "r"))) {
+ while (fgets(line, sizeof line, fp)) {
+ long long t;
+
+ if (sscanf(line, "btime %lld", &t) == 1) {
+ boot = (time_t)t;
+ break;
+ }
+ }
+ fclose(fp);
+ }
+ return boot;
+}
+
+int
+proc_info(pid_t pid, struct procinfo *p)
+{
+ struct procstat ps;
+ struct procstatus st;
+ long hz = sysconf(_SC_CLK_TCK);
+ long page = sysconf(_SC_PAGESIZE);
+
+ if (parsestat(pid, &ps) < 0)
+ return -1;
+ memset(&st, 0, sizeof st);
+ parsestatus(pid, &st);
+ if (hz <= 0)
+ hz = 100;
+ memset(p, 0, sizeof *p);
+ p->pid = pid;
+ p->ppid = ps.ppid;
+ p->pgid = ps.pgrp;
+ p->sid = ps.sid;
+ p->ruid = st.uid;
+ p->euid = st.euid;
+ p->rgid = st.gid;
+ p->egid = st.egid;
+ p->state = (char)ps.state;
+ p->nice = ps.nice;
+ p->priority = ps.priority;
+ p->nthreads = ps.num_threads;
+ p->start = boot_time() + (time_t)(ps.starttime / (unsigned long long)hz);
+ p->cpu = (ps.utime + ps.stime) / (unsigned long)hz;
+ p->vsize_kib = ps.vsize / 1024;
+ p->rss_kib = ps.rss * (page > 0 ? page / 1024 : 4);
+ if (ps.tty_nr)
+ tty_split(ps.tty_nr, &p->tty_major, &p->tty_minor);
+ strlcpy(p->comm, ps.comm, sizeof p->comm);
+ return 0;
+}
+
+int
+proc_each(proc_fn *fn, void *arg)
+{
+ struct dirent *e;
+ struct procinfo p;
+ DIR *d = opendir(ARUU_LINUX_PATH_PROC);
+
+ if (!d)
+ return -1;
+ while ((e = readdir(d))) {
+ if (!pidfile(e->d_name) || proc_info((pid_t)strtol(e->d_name, NULL, 10), &p) < 0)
+ continue;
+ if (fn(&p, arg))
+ break;
+ }
+ closedir(d);
+ return 0;
+}
+
+int
+proc_args(pid_t pid, char *buf, size_t n)
+{
+ return parsecmdline(pid, buf, n);
+}
+
+void
+proc_ttyname(unsigned major, unsigned minor, char *buf, size_t n)
+{
+ if (major == 136)
+ snprintf(buf, n, "pts/%u", minor);
+ else if (major == 4 && minor < 64)
+ snprintf(buf, n, "tty%u", minor);
+ else if (major == 4)
+ snprintf(buf, n, "ttyS%u", minor - 64);
+ else if (major == 5 && minor == 0)
+ snprintf(buf, n, "tty");
+ else
+ snprintf(buf, n, "?");
+}
+
+#endif
diff --git a/shared/libutil/proc_other.c b/shared/libutil/proc_other.c
@@ -0,0 +1,82 @@
+/* see LICENSE file for copyright and license details */
+#include "../proc.h"
+
+#include <errno.h>
+#include <string.h>
+
+/* a kernel with no backend yet: its process table is not read, and every
+ * tool that wants it says why. proc_linux.c is the one that reads it */
+#if !defined(__linux__) || defined(ARUU_FORCE_OTHER)
+
+int
+parsecmdline(pid_t pid, char *buf, size_t siz)
+{
+ (void)pid;
+ (void)buf;
+ (void)siz;
+ errno = ENOTSUP;
+ return -1;
+}
+
+int
+parsestat(pid_t pid, struct procstat *ps)
+{
+ (void)pid;
+ (void)ps;
+ errno = ENOTSUP;
+ return -1;
+}
+
+int
+parsestatus(pid_t pid, struct procstatus *pstatus)
+{
+ (void)pid;
+ (void)pstatus;
+ errno = ENOTSUP;
+ return -1;
+}
+
+int
+pidfile(const char *file)
+{
+ char *end;
+
+ errno = 0;
+ strtol(file, &end, 10);
+ return *end == '\0' && errno == 0;
+}
+
+int
+proc_each(proc_fn *fn, void *arg)
+{
+ (void)fn;
+ (void)arg;
+ errno = ENOTSUP;
+ return -1;
+}
+
+int
+proc_info(pid_t pid, struct procinfo *p)
+{
+ (void)pid;
+ memset(p, 0, sizeof *p);
+ errno = ENOTSUP;
+ return -1;
+}
+
+int
+proc_args(pid_t pid, char *buf, size_t n)
+{
+ return parsecmdline(pid, buf, n);
+}
+
+void
+proc_ttyname(unsigned major, unsigned minor, char *buf, size_t n)
+{
+ (void)major;
+ (void)minor;
+ if (n)
+ strlcpy(buf, "?", n);
+}
+
+#endif
diff --git a/shared/proc.h b/shared/proc.h
@@ -40,3 +40,34 @@ int parsestatus(pid_t pid, struct procstatus *pstatus);
int proceuid(pid_t pid, uid_t *euid);
int procuid(pid_t pid, uid_t *euid);
int pidfile(const char *file);
+
+/* the process table, as every kernel's tools want it: one row per process in
+ * words that are not any kernel's. proc_linux.c reads it from /proc, and
+ * proc_other.c says a kernel has no backend yet, so ps, pgrep and pkill
+ * are the same code everywhere and a port is one file */
+struct procinfo {
+ pid_t pid, ppid, pgid, sid;
+ uid_t ruid, euid;
+ gid_t rgid, egid;
+ unsigned tty_major, tty_minor; /* 0 0 for no terminal */
+ char state; /* R S D Z T, as ps prints it */
+ long nice, priority;
+ long nthreads;
+ time_t start; /* when it began, seconds since the epoch */
+ unsigned long cpu; /* seconds of cpu time, system and user */
+ unsigned long vsize_kib;
+ long rss_kib;
+ char comm[256];
+};
+
+typedef int proc_fn(const struct procinfo *p, void *arg);
+
+/* fn for every process there is, until it returns non zero. -1 with errno
+ * set when the table cannot be read, ENOTSUP where there is no backend */
+int proc_each(proc_fn *fn, void *arg);
+int proc_info(pid_t pid, struct procinfo *p);
+/* the command line, its words joined by spaces. -1 for a process with none,
+ * a kernel thread or a zombie */
+int proc_args(pid_t pid, char *buf, size_t n);
+/* the terminal's name as ps shows it: pts/3, tty1 or ? for none */
+void proc_ttyname(unsigned major, unsigned minor, char *buf, size_t n);