aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

ps.c (14461B)


      1 /* see LICENSE file for copyright and license details */
      2 #include <sys/ioctl.h>
      3 #include <sys/types.h>
      4 
      5 #include <ctype.h>
      6 #include <grp.h>
      7 #include <limits.h>
      8 #include <pwd.h>
      9 #include <stdio.h>
     10 #include <stdlib.h>
     11 #include <string.h>
     12 #include <time.h>
     13 #include <unistd.h>
     14 
     15 #include "proc.h"
     16 #include "util.h"
     17 
     18 /* what -o can name, and what each is headed with. a column says how to write
     19  * one process into text, so the default, -f, -l and -o all print the same
     20  * way */
     21 struct column {
     22   const char *name, *head;
     23   int         width; /* negative: left aligned */
     24   void (*put)(const struct procinfo *p, char *out, size_t n);
     25 };
     26 
     27 enum { PS_A = 1 << 0, PS_a = 1 << 1, PS_d = 1 << 2, PS_f = 1 << 3, PS_l = 1 << 4 };
     28 
     29 static int flags;
     30 
     31 /* the lists -p -t -u -U -g -G take: comma or space separated words */
     32 struct list {
     33   char **w;
     34   int    n;
     35 };
     36 
     37 static struct list          pids, ttys, users, ruser, sids, rgroups;
     38 static char                *headers[32];
     39 static const struct column *chosen[32];
     40 static int                  nchosen;
     41 static int                  allheadless; /* every -o column had its own header text, empty */
     42 
     43 static void
     44 username(uid_t uid, char *out, size_t n)
     45 {
     46   struct passwd *pw = getpwuid(uid);
     47 
     48   if (pw)
     49     snprintf(out, n, "%s", pw->pw_name);
     50   else
     51     snprintf(out, n, "%u", (unsigned)uid);
     52 }
     53 
     54 static void
     55 groupname(gid_t gid, char *out, size_t n)
     56 {
     57   struct group *gr = getgrgid(gid);
     58 
     59   if (gr)
     60     snprintf(out, n, "%s", gr->gr_name);
     61   else
     62     snprintf(out, n, "%u", (unsigned)gid);
     63 }
     64 
     65 static void
     66 hms(unsigned long secs, char *out, size_t n)
     67 {
     68   snprintf(out, n, "%02lu:%02lu:%02lu", secs / 3600, (secs % 3600) / 60, secs % 60);
     69 }
     70 
     71 static void
     72 put_user(const struct procinfo *p, char *o, size_t n)
     73 {
     74   username(p->euid, o, n);
     75 }
     76 static void
     77 put_ruser(const struct procinfo *p, char *o, size_t n)
     78 {
     79   username(p->ruid, o, n);
     80 }
     81 static void
     82 put_group(const struct procinfo *p, char *o, size_t n)
     83 {
     84   groupname(p->egid, o, n);
     85 }
     86 static void
     87 put_rgroup(const struct procinfo *p, char *o, size_t n)
     88 {
     89   groupname(p->rgid, o, n);
     90 }
     91 static void
     92 put_pid(const struct procinfo *p, char *o, size_t n)
     93 {
     94   snprintf(o, n, "%d", (int)p->pid);
     95 }
     96 static void
     97 put_ppid(const struct procinfo *p, char *o, size_t n)
     98 {
     99   snprintf(o, n, "%d", (int)p->ppid);
    100 }
    101 static void
    102 put_pgid(const struct procinfo *p, char *o, size_t n)
    103 {
    104   snprintf(o, n, "%d", (int)p->pgid);
    105 }
    106 static void
    107 put_nice(const struct procinfo *p, char *o, size_t n)
    108 {
    109   snprintf(o, n, "%ld", p->nice);
    110 }
    111 static void
    112 put_pri(const struct procinfo *p, char *o, size_t n)
    113 {
    114   snprintf(o, n, "%ld", p->priority);
    115 }
    116 static void
    117 put_vsz(const struct procinfo *p, char *o, size_t n)
    118 {
    119   snprintf(o, n, "%lu", p->vsize_kib);
    120 }
    121 static void
    122 put_sz(const struct procinfo *p, char *o, size_t n)
    123 {
    124   snprintf(o, n, "%lu", p->vsize_kib / 4);
    125 }
    126 static void
    127 put_state(const struct procinfo *p, char *o, size_t n)
    128 {
    129   snprintf(o, n, "%c", p->state);
    130 }
    131 static void
    132 put_time(const struct procinfo *p, char *o, size_t n)
    133 {
    134   hms(p->cpu, o, n);
    135 }
    136 static void
    137 put_comm(const struct procinfo *p, char *o, size_t n)
    138 {
    139   snprintf(o, n, "%s", p->comm);
    140 }
    141 static void
    142 put_zero(const struct procinfo *p, char *o, size_t n)
    143 {
    144   (void)p;
    145   snprintf(o, n, "0");
    146 }
    147 static void
    148 put_dash(const struct procinfo *p, char *o, size_t n)
    149 {
    150   (void)p;
    151   snprintf(o, n, "-");
    152 }
    153 
    154 static void
    155 put_tty(const struct procinfo *p, char *o, size_t n)
    156 {
    157   proc_ttyname(p->tty_major, p->tty_minor, o, n);
    158 }
    159 
    160 /* the command line, or the name in brackets for what has none, as a kernel
    161  * thread */
    162 static void
    163 put_args(const struct procinfo *p, char *o, size_t n)
    164 {
    165   char args[BUFSIZ];
    166 
    167   size_t len;
    168 
    169   if (proc_args(p->pid, args, sizeof args) < 0) {
    170     snprintf(o, n, "[%s]", p->comm);
    171     return;
    172   }
    173   /* the words end with the nul that ended the last, made a space */
    174   for (len = strlen(args); len && args[len - 1] == ' '; len--)
    175     args[len - 1] = '\0';
    176   snprintf(o, n, "%s", args);
    177 }
    178 
    179 /* the program's name, and with -f its command line: what CMD says */
    180 static void
    181 put_cmd(const struct procinfo *p, char *o, size_t n)
    182 {
    183   if (flags & PS_f)
    184     put_args(p, o, n);
    185   else
    186     put_comm(p, o, n);
    187 }
    188 
    189 /* how long it has run: [[dd-]hh:]mm:ss */
    190 static void
    191 put_etime(const struct procinfo *p, char *o, size_t n)
    192 {
    193   unsigned long s = time(NULL) > p->start ? (unsigned long)(time(NULL) - p->start) : 0;
    194 
    195   if (s >= 86400)
    196     snprintf(o, n, "%lu-%02lu:%02lu:%02lu", s / 86400, (s % 86400) / 3600, (s % 3600) / 60, s % 60);
    197   else if (s >= 3600)
    198     snprintf(o, n, "%02lu:%02lu:%02lu", s / 3600, (s % 3600) / 60, s % 60);
    199   else
    200     snprintf(o, n, "%02lu:%02lu", s / 60, s % 60);
    201 }
    202 
    203 /* when it began: the time of day, or the day when it was before today */
    204 static void
    205 put_stime(const struct procinfo *p, char *o, size_t n)
    206 {
    207   struct tm tm, now;
    208   time_t    t = time(NULL);
    209 
    210   localtime_r(&p->start, &tm);
    211   localtime_r(&t, &now);
    212   if (tm.tm_yday == now.tm_yday && tm.tm_year == now.tm_year)
    213     strftime(o, n, "%H:%M", &tm);
    214   else
    215     strftime(o, n, "%b%d", &tm);
    216 }
    217 
    218 /* the share of the time it has been there that it spent running */
    219 static void
    220 put_pcpu(const struct procinfo *p, char *o, size_t n)
    221 {
    222   time_t life = time(NULL) - p->start;
    223 
    224   snprintf(o, n, "%.1f", life > 0 ? 100.0 * (double)p->cpu / (double)life : 0.0);
    225 }
    226 
    227 static const struct column columns[] = {
    228     {"user", "USER", -8, put_user},
    229     {"ruser", "RUSER", -8, put_ruser},
    230     {"group", "GROUP", -8, put_group},
    231     {"rgroup", "RGROUP", -8, put_rgroup},
    232     {"uid", "UID", -8, put_user},
    233     {"pid", "PID", 5, put_pid},
    234     {"ppid", "PPID", 5, put_ppid},
    235     {"pgid", "PGID", 5, put_pgid},
    236     {"etime", "ELAPSED", 11, put_etime},
    237     {"nice", "NI", 3, put_nice},
    238     {"pcpu", "%CPU", 4, put_pcpu},
    239     {"vsz", "VSZ", 7, put_vsz},
    240     {"time", "TIME", 8, put_time},
    241     {"tty", "TT", -8, put_tty},
    242     {"comm", "COMMAND", -15, put_comm},
    243     {"args", "COMMAND", -15, put_args},
    244     /* the names of -f and -l, which are not the ones of -o */
    245     {"f", "F", 1, put_zero},
    246     {"s", "S", 1, put_state},
    247     {"c", "C", 2, put_zero},
    248     {"pri", "PRI", 3, put_pri},
    249     {"addr", "ADDR", 4, put_dash},
    250     {"sz", "SZ", 6, put_sz},
    251     {"wchan", "WCHAN", 6, put_dash},
    252     {"stime", "STIME", 5, put_stime},
    253     {"cmd", "CMD", -15, put_cmd},
    254 };
    255 
    256 static const struct column *
    257 column(const char *name)
    258 {
    259   size_t i;
    260 
    261   for (i = 0; i < sizeof columns / sizeof *columns; i++)
    262     if (!strcmp(columns[i].name, name))
    263       return &columns[i];
    264   return NULL;
    265 }
    266 
    267 static void
    268 choose(const char *name, const char *head)
    269 {
    270   const struct column *c = column(name);
    271 
    272   if (!c)
    273     eprintf("%s: unknown format keyword\n", name);
    274   if (nchosen == 32)
    275     eprintf("too many columns\n");
    276   headers[nchosen]  = (char *)(head ? head : c->head);
    277   chosen[nchosen++] = c;
    278 }
    279 
    280 /* -o's list: keywords, each with its own header after an =. a list whose
    281  * every header is empty prints no header line */
    282 static void
    283 add_format(char *arg)
    284 {
    285   char *tok, *eq;
    286 
    287   for (tok = strtok(arg, ", "); tok; tok = strtok(NULL, ", ")) {
    288     eq = strchr(tok, '=');
    289     if (eq) {
    290       *eq = '\0';
    291       choose(tok, eq + 1);
    292       if (*(eq + 1) == '\0')
    293         allheadless++;
    294     } else {
    295       choose(tok, NULL);
    296     }
    297   }
    298 }
    299 
    300 static void
    301 add_list(struct list *l, char *arg)
    302 {
    303   char *tok;
    304 
    305   for (tok = strtok(arg, ", "); tok; tok = strtok(NULL, ", ")) {
    306     l->w         = ereallocarray(l->w, l->n + 1, sizeof(*l->w));
    307     l->w[l->n++] = tok;
    308   }
    309 }
    310 
    311 static int
    312 in_list(const struct list *l, const char *s)
    313 {
    314   int i;
    315 
    316   for (i = 0; i < l->n; i++)
    317     if (!strcmp(l->w[i], s))
    318       return 1;
    319   return 0;
    320 }
    321 
    322 static int
    323 user_in(const struct list *l, uid_t uid)
    324 {
    325   char name[64], num[16];
    326 
    327   username(uid, name, sizeof name);
    328   snprintf(num, sizeof num, "%u", (unsigned)uid);
    329   return in_list(l, name) || in_list(l, num);
    330 }
    331 
    332 static int
    333 group_in(const struct list *l, gid_t gid)
    334 {
    335   char name[64], num[16];
    336 
    337   groupname(gid, name, sizeof name);
    338   snprintf(num, sizeof num, "%u", (unsigned)gid);
    339   return in_list(l, name) || in_list(l, num);
    340 }
    341 
    342 /* a terminal as -t names it: pts/3, or tty1, or the same without the dir */
    343 static int
    344 tty_in(const struct list *l, const struct procinfo *p)
    345 {
    346   char name[32];
    347 
    348   proc_ttyname(p->tty_major, p->tty_minor, name, sizeof name);
    349   return in_list(l, name) || (!strncmp(name, "pts/", 4) && in_list(l, name + 4));
    350 }
    351 
    352 static char  mytty[32];
    353 static uid_t myuid;
    354 static int   have_tty;
    355 
    356 /* whether a process is one of those asked for */
    357 static int
    358 wanted(const struct procinfo *p)
    359 {
    360   char num[16];
    361   int  selected = 0, listed = 0;
    362 
    363   snprintf(num, sizeof num, "%d", (int)p->pid);
    364   if (pids.n) {
    365     listed = 1;
    366     selected |= in_list(&pids, num);
    367   }
    368   if (ttys.n) {
    369     listed = 1;
    370     selected |= tty_in(&ttys, p);
    371   }
    372   if (users.n) {
    373     listed = 1;
    374     selected |= user_in(&users, p->euid);
    375   }
    376   if (ruser.n) {
    377     listed = 1;
    378     selected |= user_in(&ruser, p->ruid);
    379   }
    380   if (rgroups.n) {
    381     listed = 1;
    382     selected |= group_in(&rgroups, p->rgid);
    383   }
    384   if (sids.n) {
    385     listed = 1;
    386     selected |= in_list(&sids, (snprintf(num, sizeof num, "%d", (int)p->sid), num));
    387   }
    388   if (flags & PS_A)
    389     return 1;
    390   if (flags & PS_a) {
    391     if (p->pid != p->sid && (p->tty_major || p->tty_minor))
    392       return 1;
    393     return selected;
    394   }
    395   if (flags & PS_d) {
    396     if (p->pid != p->sid)
    397       return 1;
    398     return selected;
    399   }
    400   if (listed)
    401     return selected;
    402   /* nothing asked for: the invoker's, on the invoker's terminal */
    403   if (p->euid != myuid)
    404     return 0;
    405   if (have_tty) {
    406     char name[32];
    407 
    408     proc_ttyname(p->tty_major, p->tty_minor, name, sizeof name);
    409     return !strcmp(name, mytty);
    410   }
    411   return 1;
    412 }
    413 
    414 static int width;
    415 
    416 static int
    417 show(const struct procinfo *p, void *arg)
    418 {
    419   char   line[BUFSIZ * 2], cell[BUFSIZ];
    420   size_t at = 0;
    421   int    i;
    422 
    423   (void)arg;
    424   if (!wanted(p))
    425     return 0;
    426   for (i = 0; i < nchosen; i++) {
    427     chosen[i]->put(p, cell, sizeof cell);
    428     /* the last column runs as long as it is */
    429     if (i == nchosen - 1)
    430       at += (size_t)snprintf(line + at, sizeof line - at, "%s%s", i ? " " : "", cell);
    431     else
    432       at += (size_t)snprintf(
    433           line + at, sizeof line - at, "%s%*s", i ? " " : "", chosen[i]->width, cell
    434       );
    435     if (at >= sizeof line)
    436       at = sizeof line - 1;
    437   }
    438   if (width && at > (size_t)width)
    439     line[width] = '\0';
    440   puts(line);
    441   return 0;
    442 }
    443 
    444 static void
    445 usage(void)
    446 {
    447   eprintf(
    448       "usage: %s [-aAdefl] [-g grouplist] [-G grouplist] [-o format]... [-p proclist]\n"
    449       "          [-t termlist] [-u userlist] [-U userlist]\n",
    450       argv0
    451   );
    452 }
    453 
    454 // ?man ps: report process status
    455 // ?man ps writes information about processes: by default those of the
    456 // ?man invoker on the terminal it was run from. the processes of every
    457 // ?man kernel it has a process table backend for are written the same
    458 int
    459 main(int argc, char *argv[])
    460 {
    461   char          *name;
    462   int            i;
    463   struct winsize w = {0};
    464 
    465   ARGBEGIN
    466   {
    467     // ?man -A: every process
    468     case 'A':
    469       flags |= PS_A;
    470       break;
    471     // ?man -e: every process, as -A
    472     case 'e':
    473       flags |= PS_A;
    474       break;
    475     // ?man -a: the processes with a terminal that are not session leaders
    476     case 'a':
    477       flags |= PS_a;
    478       break;
    479     // ?man -d: every process but the session leaders
    480     case 'd':
    481       flags |= PS_d;
    482       break;
    483     // ?man -f: a full listing, with the owner, the parent and the start
    484     case 'f':
    485       flags |= PS_f;
    486       break;
    487     // ?man -l: a long listing
    488     case 'l':
    489       flags |= PS_l;
    490       break;
    491     // ?man -n: accepted and ignored, the name list of the system is not used
    492     case 'n':
    493       (void)EARGF(usage());
    494       break;
    495     // ?man -o:format: the columns written, keywords with an optional =header
    496     case 'o':
    497       add_format(EARGF(usage()));
    498       break;
    499     // ?man -p:proclist: only these processes
    500     case 'p':
    501       add_list(&pids, EARGF(usage()));
    502       break;
    503     // ?man -t:termlist: only the processes on these terminals
    504     case 't':
    505       add_list(&ttys, EARGF(usage()));
    506       break;
    507     // ?man -u:userlist: only the processes of these effective users
    508     case 'u':
    509       add_list(&users, EARGF(usage()));
    510       break;
    511     // ?man -U:userlist: only the processes of these real users
    512     case 'U':
    513       add_list(&ruser, EARGF(usage()));
    514       break;
    515     // ?man -g:sidlist: only the processes of these sessions
    516     case 'g':
    517       add_list(&sids, EARGF(usage()));
    518       break;
    519     // ?man -G:grouplist: only the processes of these real groups
    520     case 'G':
    521       add_list(&rgroups, EARGF(usage()));
    522       break;
    523     default:
    524       usage();
    525   }
    526   ARGEND;
    527 
    528   if (argc)
    529     usage();
    530 
    531   /* the default, -f and -l are named lists of columns */
    532   if (!nchosen) {
    533     const char *set[]  = {"pid", "tty", "time", "cmd"};
    534     const char *full[] = {"uid", "pid", "ppid", "c", "stime", "tty", "time", "cmd"};
    535     const char *lng[]  = {
    536         "f",
    537         "s",
    538         "uid",
    539         "pid",
    540         "ppid",
    541         "c",
    542         "pri",
    543         "nice",
    544         "addr",
    545         "sz",
    546         "wchan",
    547         "tty",
    548         "time",
    549         "cmd"
    550     };
    551     const char **l = (flags & PS_l) ? lng : (flags & PS_f) ? full : set;
    552     size_t       k, n = (flags & PS_l)   ? sizeof lng / sizeof *lng
    553                         : (flags & PS_f) ? sizeof full / sizeof *full
    554                                          : sizeof set / sizeof *set;
    555 
    556     for (k = 0; k < n; k++)
    557       choose(l[k], NULL);
    558   }
    559 
    560   if ((name = ttyname(0))) {
    561     unsigned        maj = 0, min = 0;
    562     struct procinfo me;
    563 
    564     if (proc_info(getpid(), &me) == 0) {
    565       maj = me.tty_major;
    566       min = me.tty_minor;
    567     }
    568     proc_ttyname(maj, min, mytty, sizeof mytty);
    569     have_tty = mytty[0] != '?' || mytty[1];
    570     (void)name;
    571   }
    572   myuid = geteuid();
    573   if (ioctl(1, TIOCGWINSZ, &w) == 0)
    574     width = w.ws_col;
    575 
    576   /* a header line, unless every column was given an empty header */
    577   if (allheadless < nchosen) {
    578     char   head[BUFSIZ];
    579     size_t at = 0;
    580 
    581     for (i = 0; i < nchosen; i++) {
    582       if (i == nchosen - 1)
    583         at += (size_t)snprintf(head + at, sizeof head - at, "%s%s", i ? " " : "", headers[i]);
    584       else
    585         at += (size_t)snprintf(
    586             head + at, sizeof head - at, "%s%*s", i ? " " : "", chosen[i]->width, headers[i]
    587         );
    588       if (at >= sizeof head)
    589         at = sizeof head - 1;
    590     }
    591     puts(head);
    592   }
    593   if (proc_each(show, NULL) < 0)
    594     eprintf("the process table cannot be read:");
    595   return fshut(stdout, "<stdout>");
    596 }