1 /* vi: set sw=4 ts=4: */
3 * Mini ps implementation(s) for busybox
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6 * Fix for SELinux Support:(c)2007 Hiroshi Shinji <shiroshi@my.email.ne.jp>
7 * (c)2007 Yuichi Nakamura <ynakam@hitachisoft.jp>
9 * Licensed under GPLv2, see file LICENSE in this source tree.
12 //usage:#if ENABLE_DESKTOP
14 //usage:#define ps_trivial_usage
15 //usage: "[-o COL1,COL2=HEADER]" IF_FEATURE_SHOW_THREADS(" [-T]")
16 //usage:#define ps_full_usage "\n\n"
17 //usage: "Show list of processes\n"
18 //usage: "\n -o COL1,COL2=HEADER Select columns for display"
19 //usage: IF_FEATURE_SHOW_THREADS(
20 //usage: "\n -T Show threads"
23 //usage:#else /* !ENABLE_DESKTOP */
25 //usage:#if !ENABLE_SELINUX && !ENABLE_FEATURE_PS_WIDE
26 //usage:#define USAGE_PS "\nThis version of ps accepts no options"
28 //usage:#define USAGE_PS ""
31 //usage:#define ps_trivial_usage
33 //usage:#define ps_full_usage "\n\n"
34 //usage: "Show list of processes\n"
37 //usage: "\n -Z Show selinux context"
39 //usage: IF_FEATURE_PS_WIDE(
40 //usage: "\n w Wide output"
42 //usage: IF_FEATURE_PS_LONG(
43 //usage: "\n l Long output"
45 //usage: IF_FEATURE_SHOW_THREADS(
46 //usage: "\n T Show threads"
49 //usage:#endif /* ENABLE_DESKTOP */
51 //usage:#define ps_example_usage
53 //usage: " PID Uid Gid State Command\n"
54 //usage: " 1 root root S init\n"
55 //usage: " 2 root root S [kflushd]\n"
56 //usage: " 3 root root S [kupdate]\n"
57 //usage: " 4 root root S [kpiod]\n"
58 //usage: " 5 root root S [kswapd]\n"
59 //usage: " 742 andersen andersen S [bash]\n"
60 //usage: " 743 andersen andersen S -bash\n"
61 //usage: " 745 root root S [getty]\n"
62 //usage: " 2990 andersen andersen R ps\n"
65 #include "common_bufsiz.h"
67 # include <sys/sysinfo.h>
70 /* Absolute maximum on output line length */
71 enum { MAX_WIDTH = 2*1024 };
73 #if ENABLE_FEATURE_PS_TIME || ENABLE_FEATURE_PS_LONG
74 static unsigned long get_uptime(void)
78 if (sysinfo(&info) < 0)
83 char buf[sizeof(uptime)*3 + 2];
84 /* /proc/uptime is "UPTIME_SEC.NN IDLE_SEC.NN\n"
85 * (where IDLE is cumulative over all CPUs)
87 if (open_read_close("/proc/uptime", buf, sizeof(buf)) <= 0)
88 bb_perror_msg_and_die("can't read '%s'", "/proc/uptime");
89 buf[sizeof(buf)-1] = '\0';
90 sscanf(buf, "%lu", &uptime);
94 if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
103 #include <sys/times.h> /* for times() */
105 # define AT_CLKTCK 17
109 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
110 * specifies (for XSI-conformant systems) following default columns
111 * (l and f mark columns shown with -l and -f respectively):
112 * F l Flags (octal and additive) associated with the process (??)
113 * S l The state of the process
114 * UID f,l The user ID; the login name is printed with -f
116 * PPID f,l The parent process
117 * C f,l Processor utilization
118 * PRI l The priority of the process; higher numbers mean lower priority
120 * ADDR l The address of the process
121 * SZ l The size in blocks of the core image of the process
122 * WCHAN l The event for which the process is waiting or sleeping
123 * STIME f Starting time of the process
124 * TTY The controlling terminal for the process
125 * TIME The cumulative execution time for the process
126 * CMD The command name; the full command line is shown with -f
132 void (*f)(char *buf, int size, const procps_status_t *ps);
142 unsigned terminal_width;
143 #if ENABLE_FEATURE_PS_TIME
145 unsigned long seconds_since_boot;
148 #define G (*(struct globals*)bb_common_bufsiz1)
150 #define out_cnt (G.out_cnt )
151 #define print_header (G.print_header )
152 #define need_flags (G.need_flags )
153 #define buffer (G.buffer )
154 #define terminal_width (G.terminal_width )
155 #define kernel_HZ (G.kernel_HZ )
156 #define INIT_G() do { setup_common_bufsiz(); } while (0)
158 #if ENABLE_FEATURE_PS_TIME
159 /* for ELF executables, notes are pushed before environment and args */
160 static uintptr_t find_elf_note(uintptr_t findme)
162 uintptr_t *ep = (uintptr_t *) environ;
167 if (ep[0] == findme) {
175 #if ENABLE_FEATURE_PS_UNUSUAL_SYSTEMS
176 static unsigned get_HZ_by_waiting(void)
178 struct timeval tv1, tv2;
179 unsigned t1, t2, r, hz;
180 unsigned cnt = cnt; /* for compiler */
185 /* Wait for times() to reach new tick */
190 gettimeofday(&tv2, NULL);
194 tv1.tv_usec = tv2.tv_usec;
196 /* Wait exactly one times() tick */
200 gettimeofday(&tv2, NULL);
202 /* Calculate ticks per sec, rounding up to even */
203 diff = tv2.tv_usec - tv1.tv_usec;
204 if (diff <= 0) diff += 1000000;
205 hz = 1000000u / (unsigned)diff;
208 /* Count how many same hz values we saw */
214 } while (cnt < 3); /* exit if saw 3 same values */
219 static inline unsigned get_HZ_by_waiting(void)
226 static unsigned get_kernel_HZ(void)
231 /* Works for ELF only, Linux 2.4.0+ */
232 kernel_HZ = find_elf_note(AT_CLKTCK);
233 if (kernel_HZ == (unsigned)-1)
234 kernel_HZ = get_HZ_by_waiting();
236 G.seconds_since_boot = get_uptime();
242 /* Print value to buf, max size+1 chars (including trailing '\0') */
244 static void func_user(char *buf, int size, const procps_status_t *ps)
247 safe_strncpy(buf, get_cached_username(ps->uid), size+1);
249 /* "compatible" version, but it's larger */
250 /* procps 2.18 shows numeric UID if name overflows the field */
251 /* TODO: get_cached_username() returns numeric string if
252 * user has no passwd record, we will display it
253 * left-justified here; too long usernames are shown
254 * as _right-justified_ IDs. Is it worth fixing? */
255 const char *user = get_cached_username(ps->uid);
256 if (strlen(user) <= size)
257 safe_strncpy(buf, user, size+1);
259 sprintf(buf, "%*u", size, (unsigned)ps->uid);
263 static void func_group(char *buf, int size, const procps_status_t *ps)
265 safe_strncpy(buf, get_cached_groupname(ps->gid), size+1);
268 static void func_comm(char *buf, int size, const procps_status_t *ps)
270 safe_strncpy(buf, ps->comm, size+1);
273 static void func_state(char *buf, int size, const procps_status_t *ps)
275 safe_strncpy(buf, ps->state, size+1);
278 static void func_args(char *buf, int size, const procps_status_t *ps)
280 read_cmdline(buf, size+1, ps->pid, ps->comm);
283 static void func_pid(char *buf, int size, const procps_status_t *ps)
285 sprintf(buf, "%*u", size, ps->pid);
288 static void func_ppid(char *buf, int size, const procps_status_t *ps)
290 sprintf(buf, "%*u", size, ps->ppid);
293 static void func_pgid(char *buf, int size, const procps_status_t *ps)
295 sprintf(buf, "%*u", size, ps->pgid);
298 static void put_lu(char *buf, int size, unsigned long u)
302 /* see http://en.wikipedia.org/wiki/Tera */
303 smart_ulltoa4(u, buf4, " mgtpezy")[0] = '\0';
304 sprintf(buf, "%.*s", size, buf4);
307 static void func_vsz(char *buf, int size, const procps_status_t *ps)
309 put_lu(buf, size, ps->vsz);
312 static void func_rss(char *buf, int size, const procps_status_t *ps)
314 put_lu(buf, size, ps->rss);
317 static void func_tty(char *buf, int size, const procps_status_t *ps)
321 if (ps->tty_major) /* tty field of "0" means "no tty" */
322 snprintf(buf, size+1, "%u,%u", ps->tty_major, ps->tty_minor);
325 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
327 static void func_rgroup(char *buf, int size, const procps_status_t *ps)
329 safe_strncpy(buf, get_cached_groupname(ps->rgid), size+1);
332 static void func_ruser(char *buf, int size, const procps_status_t *ps)
334 safe_strncpy(buf, get_cached_username(ps->ruid), size+1);
337 static void func_nice(char *buf, int size, const procps_status_t *ps)
339 sprintf(buf, "%*d", size, ps->niceness);
344 #if ENABLE_FEATURE_PS_TIME
346 static void func_etime(char *buf, int size, const procps_status_t *ps)
348 /* elapsed time [[dd-]hh:]mm:ss; here only mm:ss */
352 mm = ps->start_time / get_kernel_HZ();
353 /* must be after get_kernel_HZ()! */
354 mm = G.seconds_since_boot - mm;
357 snprintf(buf, size+1, "%3lu:%02u", mm, ss);
360 static void func_time(char *buf, int size, const procps_status_t *ps)
362 /* cumulative time [[dd-]hh:]mm:ss; here only mm:ss */
366 mm = (ps->utime + ps->stime) / get_kernel_HZ();
369 snprintf(buf, size+1, "%3lu:%02u", mm, ss);
375 static void func_label(char *buf, int size, const procps_status_t *ps)
377 safe_strncpy(buf, ps->context ? ps->context : "unknown", size+1);
382 static void func_nice(char *buf, int size, const procps_status_t *ps)
387 static void func_pcpu(char *buf, int size, const procps_status_t *ps)
392 static const ps_out_t out_spec[] = {
393 /* Mandated by http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html: */
394 { 8 , "user" ,"USER" ,func_user ,PSSCAN_UIDGID },
395 { 8 , "group" ,"GROUP" ,func_group ,PSSCAN_UIDGID },
396 { 16 , "comm" ,"COMMAND",func_comm ,PSSCAN_COMM },
397 { MAX_WIDTH , "args" ,"COMMAND",func_args ,PSSCAN_COMM },
398 { 5 , "pid" ,"PID" ,func_pid ,PSSCAN_PID },
399 { 5 , "ppid" ,"PPID" ,func_ppid ,PSSCAN_PPID },
400 { 5 , "pgid" ,"PGID" ,func_pgid ,PSSCAN_PGID },
401 #if ENABLE_FEATURE_PS_TIME
402 { sizeof("ELAPSED")-1, "etime" ,"ELAPSED",func_etime ,PSSCAN_START_TIME },
404 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
405 { 5 , "nice" ,"NI" ,func_nice ,PSSCAN_NICE },
406 { 8 , "rgroup","RGROUP" ,func_rgroup,PSSCAN_RUIDGID },
407 { 8 , "ruser" ,"RUSER" ,func_ruser ,PSSCAN_RUIDGID },
408 // { 5 , "pcpu" ,"%CPU" ,func_pcpu ,PSSCAN_ },
410 #if ENABLE_FEATURE_PS_TIME
411 { 6 , "time" ,"TIME" ,func_time ,PSSCAN_STIME | PSSCAN_UTIME },
413 { 6 , "tty" ,"TT" ,func_tty ,PSSCAN_TTY },
414 { 4 , "vsz" ,"VSZ" ,func_vsz ,PSSCAN_VSZ },
415 /* Not mandated, but useful: */
416 { 4 , "stat" ,"STAT" ,func_state ,PSSCAN_STATE },
417 { 4 , "rss" ,"RSS" ,func_rss ,PSSCAN_RSS },
419 { 35 , "label" ,"LABEL" ,func_label ,PSSCAN_CONTEXT },
423 static ps_out_t* new_out_t(void)
425 out = xrealloc_vector(out, 2, out_cnt);
426 return &out[out_cnt++];
429 static const ps_out_t* find_out_spec(const char *name)
432 char buf[ARRAY_SIZE(out_spec)*7 + 1];
435 for (i = 0; i < ARRAY_SIZE(out_spec); i++) {
436 if (strncmp(name, out_spec[i].name6, 6) == 0)
438 p += sprintf(p, "%.6s,", out_spec[i].name6);
441 bb_error_msg_and_die("bad -o argument '%s', supported arguments: %s", name, buf);
444 static void parse_o(char* opt)
447 // POSIX: "-o is blank- or comma-separated list" (FIXME)
450 comma = strchr(opt, ',');
451 equal = strchr(opt, '=');
452 if (comma && (!equal || equal > comma)) {
454 *new_out_t() = *find_out_spec(opt);
461 // opt points to last spec in comma separated list.
462 // This one can have =HEADER part.
466 *new = *find_out_spec(opt);
469 new->header = equal + 1;
470 // POSIX: the field widths shall be ... at least as wide as
471 // the header text (default or overridden value).
472 // If the header text is null, such as -o user=,
473 // the field width shall be at least as wide as the
474 // default header text
475 if (new->header[0]) {
476 new->width = strlen(new->header);
483 static void alloc_line_buffer(void)
487 for (i = 0; i < out_cnt; i++) {
488 need_flags |= out[i].ps_flags;
489 if (out[i].header[0]) {
492 width += out[i].width + 1; /* "FIELD " */
493 if ((int)(width - terminal_width) > 0) {
494 /* The rest does not fit on the screen */
495 //out[i].width -= (width - terminal_width - 1);
501 if (!is_selinux_enabled())
502 need_flags &= ~PSSCAN_CONTEXT;
504 buffer = xmalloc(width + 1); /* for trailing \0 */
507 static void format_header(void)
520 if (++i == out_cnt) /* do not pad last field */
522 p += sprintf(p, "%-*s ", op->width, op->header);
524 strcpy(p, op->header);
526 printf("%.*s\n", terminal_width, buffer);
529 static void format_process(const procps_status_t *ps)
534 if (out_cnt) while (1) {
535 out[i].f(p, out[i].width, ps);
536 // POSIX: Any field need not be meaningful in all
537 // implementations. In such a case a hyphen ( '-' )
538 // should be output in place of the field value.
545 len = out[i].width - len + 1;
546 if (++i == out_cnt) /* do not pad last field */
548 p += sprintf(p, "%*s", len, "");
550 printf("%.*s\n", terminal_width, buffer);
554 # define SELINUX_O_PREFIX "label,"
555 # define DEFAULT_O_STR (SELINUX_O_PREFIX "pid,user" IF_FEATURE_PS_TIME(",time") ",args")
557 # define DEFAULT_O_STR ("pid,user" IF_FEATURE_PS_TIME(",time") ",args")
560 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
561 int ps_main(int argc UNUSED_PARAM, char **argv)
564 llist_t* opt_o = NULL;
565 char default_o[sizeof(DEFAULT_O_STR)];
576 OPT_T = (1 << 8) * ENABLE_FEATURE_SHOW_THREADS,
582 // -a Write information for all processes associated with terminals
583 // Implementations may omit session leaders from this list
584 // -A Write information for all processes
585 // -d Write information for all processes, except session leaders
586 // -e Write information for all processes (equivalent to -A)
587 // -f Generate a full listing
588 // -l Generate a long listing
589 // -o col1,col2,col3=header
590 // Select which columns to display
591 /* We allow (and ignore) most of the above. FIXME.
592 * -T is picked for threads (POSIX hasn't standardized it).
593 * procps v3.2.7 supports -T and shows tids as SPID column,
594 * it also supports -L where it shows tids as LWP column.
596 opt_complementary = "o::";
597 opt = getopt32(argv, "Zo:aAdefl"IF_FEATURE_SHOW_THREADS("T"), &opt_o);
600 parse_o(llist_pop(&opt_o));
603 /* Below: parse_o() needs char*, NOT const char*,
604 * can't pass it constant string. Need to make a copy first.
607 if (!(opt & OPT_Z) || !is_selinux_enabled()) {
608 /* no -Z or no SELinux: do not show LABEL */
609 strcpy(default_o, DEFAULT_O_STR + sizeof(SELINUX_O_PREFIX)-1);
613 strcpy(default_o, DEFAULT_O_STR);
617 #if ENABLE_FEATURE_SHOW_THREADS
619 need_flags |= PSSCAN_TASKS;
622 /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
623 * and such large widths */
624 terminal_width = MAX_WIDTH;
626 terminal_width = get_terminal_width(0);
627 if (--terminal_width > MAX_WIDTH)
628 terminal_width = MAX_WIDTH;
634 while ((p = procps_scan(p, need_flags)) != NULL) {
642 #else /* !ENABLE_DESKTOP */
645 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
646 int ps_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
649 int psscan_flags = PSSCAN_PID | PSSCAN_UIDGID
650 | PSSCAN_STATE | PSSCAN_VSZ | PSSCAN_COMM;
651 unsigned terminal_width IF_NOT_FEATURE_PS_WIDE(= 79);
653 OPT_Z = (1 << 0) * ENABLE_SELINUX,
654 OPT_T = (1 << ENABLE_SELINUX) * ENABLE_FEATURE_SHOW_THREADS,
655 OPT_l = (1 << ENABLE_SELINUX) * (1 << ENABLE_FEATURE_SHOW_THREADS) * ENABLE_FEATURE_PS_LONG,
657 #if ENABLE_FEATURE_PS_LONG
658 time_t now = now; /* for compiler */
659 unsigned long uptime = uptime;
661 /* If we support any options, parse argv */
662 #if ENABLE_SELINUX || ENABLE_FEATURE_SHOW_THREADS || ENABLE_FEATURE_PS_WIDE || ENABLE_FEATURE_PS_LONG
664 # if ENABLE_FEATURE_PS_WIDE
665 /* -w is a bit complicated */
667 opt_complementary = "-:ww";
668 opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T")IF_FEATURE_PS_LONG("l")
670 /* if w is given once, GNU ps sets the width to 132,
671 * if w is given more than once, it is "unlimited"
674 terminal_width = (w_count == 1) ? 132 : MAX_WIDTH;
676 terminal_width = get_terminal_width(0);
678 if (--terminal_width > MAX_WIDTH)
679 terminal_width = MAX_WIDTH;
682 /* -w is not supported, only -Z and/or -T */
683 opt_complementary = "-";
684 opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T")IF_FEATURE_PS_LONG("l"));
688 if ((opts & OPT_Z) && is_selinux_enabled()) {
689 psscan_flags = PSSCAN_PID | PSSCAN_CONTEXT
690 | PSSCAN_STATE | PSSCAN_COMM;
691 puts(" PID CONTEXT STAT COMMAND");
695 psscan_flags = PSSCAN_STATE | PSSCAN_UIDGID | PSSCAN_PID | PSSCAN_PPID
696 | PSSCAN_TTY | PSSCAN_STIME | PSSCAN_UTIME | PSSCAN_COMM
697 | PSSCAN_VSZ | PSSCAN_RSS;
698 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
704 * -PRI The priority of the process; higher numbers mean lower priority
706 * -ADDR The address of the process (?)
707 * SZ The size in blocks of the core image
708 * -WCHAN The event for which the process is waiting or sleeping
710 * TIME The cumulative execution time
712 * We don't show fields marked with '-'.
713 * We show VSZ and RSS instead of SZ.
714 * We also show STIME (standard says that -f shows it, -l doesn't).
716 puts("S UID PID PPID VSZ RSS TTY STIME TIME CMD");
717 # if ENABLE_FEATURE_PS_LONG
719 uptime = get_uptime();
723 puts(" PID USER VSZ STAT COMMAND");
726 psscan_flags |= PSSCAN_TASKS;
731 while ((p = procps_scan(p, psscan_flags)) != NULL) {
734 if (psscan_flags & PSSCAN_CONTEXT) {
735 len = printf("%5u %-32.32s %s ",
737 p->context ? p->context : "unknown",
743 smart_ulltoa5(p->vsz, buf6, " mgtpezy")[0] = '\0';
744 #if ENABLE_FEATURE_PS_LONG
746 char bufr[6], stime_str[6];
747 char tty[2 * sizeof(int)*3 + 2];
749 unsigned sut = (p->stime + p->utime) / 100;
750 unsigned elapsed = uptime - (p->start_time / 100);
751 time_t start = now - elapsed;
752 struct tm *tm = localtime(&start);
754 smart_ulltoa5(p->rss, bufr, " mgtpezy")[0] = '\0';
756 if (p->tty_major == 136)
757 /* It should be pts/N, not ptsN, but N > 9
758 * will overflow field width...
760 endp = stpcpy(tty, "pts");
762 if (p->tty_major == 4) {
763 endp = stpcpy(tty, "tty");
764 if (p->tty_minor >= 64) {
770 endp = tty + sprintf(tty, "%d:", p->tty_major);
771 strcpy(endp, utoa(p->tty_minor));
773 strftime(stime_str, 6, (elapsed >= (24 * 60 * 60)) ? "%b%d" : "%H:%M", tm);
775 // S UID PID PPID VSZ RSS TTY STIME TIME CMD
776 len = printf("%c %5u %5u %5u %5s %5s %-5s %s %02u:%02u:%02u ",
777 p->state[0], p->uid, p->pid, p->ppid, buf6, bufr, tty,
778 stime_str, sut / 3600, (sut % 3600) / 60, sut % 60);
782 const char *user = get_cached_username(p->uid);
783 len = printf("%5u %-8.8s %s %s ",
784 p->pid, user, buf6, p->state);
789 int sz = terminal_width - len;
792 read_cmdline(buf, sz, p->pid, p->comm);
797 if (ENABLE_FEATURE_CLEAN_UP)
798 clear_username_cache();
802 #endif /* !ENABLE_DESKTOP */