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.
15 //config: ps gives a snapshot of the current processes.
17 //config:config FEATURE_PS_WIDE
18 //config: bool "Enable wide output option (-w)"
20 //config: depends on PS && !DESKTOP
22 //config: Support argument 'w' for wide output.
23 //config: If given once, 132 chars are printed, and if given more
24 //config: than once, the length is unlimited.
26 //config:config FEATURE_PS_LONG
27 //config: bool "Enable long output option (-l)"
29 //config: depends on PS && !DESKTOP
31 //config: Support argument 'l' for long output.
32 //config: Adds fields PPID, RSS, START, TIME & TTY
34 //config:config FEATURE_PS_TIME
35 //config: bool "Enable time and elapsed time output"
37 //config: depends on PS && DESKTOP
38 //config: select PLATFORM_LINUX
40 //config: Support -o time and -o etime output specifiers.
42 //config:config FEATURE_PS_ADDITIONAL_COLUMNS
43 //config: bool "Enable additional ps columns"
45 //config: depends on PS && DESKTOP
47 //config: Support -o rgroup, -o ruser, -o nice output specifiers.
49 //config:config FEATURE_PS_UNUSUAL_SYSTEMS
50 //config: bool "Support Linux prior to 2.4.0 and non-ELF systems"
52 //config: depends on FEATURE_PS_TIME
54 //config: Include support for measuring HZ on old kernels and non-ELF systems
55 //config: (if you are on Linux 2.4.0+ and use ELF, you don't need this)
57 //applet:IF_PS(APPLET(ps, BB_DIR_BIN, BB_SUID_DROP))
59 //kbuild:lib-$(CONFIG_PS) += ps.o
61 //usage:#if ENABLE_DESKTOP
63 //usage:#define ps_trivial_usage
64 //usage: "[-o COL1,COL2=HEADER]" IF_FEATURE_SHOW_THREADS(" [-T]")
65 //usage:#define ps_full_usage "\n\n"
66 //usage: "Show list of processes\n"
67 //usage: "\n -o COL1,COL2=HEADER Select columns for display"
68 //usage: IF_FEATURE_SHOW_THREADS(
69 //usage: "\n -T Show threads"
72 //usage:#else /* !ENABLE_DESKTOP */
74 //usage:#if !ENABLE_SELINUX && !ENABLE_FEATURE_PS_WIDE
75 //usage:#define USAGE_PS "\nThis version of ps accepts no options"
77 //usage:#define USAGE_PS ""
80 //usage:#define ps_trivial_usage
82 //usage:#define ps_full_usage "\n\n"
83 //usage: "Show list of processes\n"
86 //usage: "\n -Z Show selinux context"
88 //usage: IF_FEATURE_PS_WIDE(
89 //usage: "\n w Wide output"
91 //usage: IF_FEATURE_PS_LONG(
92 //usage: "\n l Long output"
94 //usage: IF_FEATURE_SHOW_THREADS(
95 //usage: "\n T Show threads"
98 //usage:#endif /* ENABLE_DESKTOP */
100 //usage:#define ps_example_usage
102 //usage: " PID Uid Gid State Command\n"
103 //usage: " 1 root root S init\n"
104 //usage: " 2 root root S [kflushd]\n"
105 //usage: " 3 root root S [kupdate]\n"
106 //usage: " 4 root root S [kpiod]\n"
107 //usage: " 5 root root S [kswapd]\n"
108 //usage: " 742 andersen andersen S [bash]\n"
109 //usage: " 743 andersen andersen S -bash\n"
110 //usage: " 745 root root S [getty]\n"
111 //usage: " 2990 andersen andersen R ps\n"
114 #include "common_bufsiz.h"
116 # include <sys/sysinfo.h>
119 /* Absolute maximum on output line length */
120 enum { MAX_WIDTH = 2*1024 };
122 #if ENABLE_FEATURE_PS_TIME || ENABLE_FEATURE_PS_LONG
123 static unsigned long get_uptime(void)
127 if (sysinfo(&info) < 0)
131 unsigned long uptime;
132 char buf[sizeof(uptime)*3 + 2];
133 /* /proc/uptime is "UPTIME_SEC.NN IDLE_SEC.NN\n"
134 * (where IDLE is cumulative over all CPUs)
136 if (open_read_close("/proc/uptime", buf, sizeof(buf)) <= 0)
137 bb_perror_msg_and_die("can't read '%s'", "/proc/uptime");
138 buf[sizeof(buf)-1] = '\0';
139 sscanf(buf, "%lu", &uptime);
143 if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
152 #include <sys/times.h> /* for times() */
154 # define AT_CLKTCK 17
158 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
159 * specifies (for XSI-conformant systems) following default columns
160 * (l and f mark columns shown with -l and -f respectively):
161 * F l Flags (octal and additive) associated with the process (??)
162 * S l The state of the process
163 * UID f,l The user ID; the login name is printed with -f
165 * PPID f,l The parent process
166 * C f,l Processor utilization
167 * PRI l The priority of the process; higher numbers mean lower priority
169 * ADDR l The address of the process
170 * SZ l The size in blocks of the core image of the process
171 * WCHAN l The event for which the process is waiting or sleeping
172 * STIME f Starting time of the process
173 * TTY The controlling terminal for the process
174 * TIME The cumulative execution time for the process
175 * CMD The command name; the full command line is shown with -f
181 void (*f)(char *buf, int size, const procps_status_t *ps);
191 unsigned terminal_width;
192 #if ENABLE_FEATURE_PS_TIME
194 unsigned long seconds_since_boot;
197 #define G (*(struct globals*)bb_common_bufsiz1)
199 #define out_cnt (G.out_cnt )
200 #define print_header (G.print_header )
201 #define need_flags (G.need_flags )
202 #define buffer (G.buffer )
203 #define terminal_width (G.terminal_width )
204 #define kernel_HZ (G.kernel_HZ )
205 #define INIT_G() do { setup_common_bufsiz(); } while (0)
207 #if ENABLE_FEATURE_PS_TIME
208 /* for ELF executables, notes are pushed before environment and args */
209 static uintptr_t find_elf_note(uintptr_t findme)
211 uintptr_t *ep = (uintptr_t *) environ;
216 if (ep[0] == findme) {
224 #if ENABLE_FEATURE_PS_UNUSUAL_SYSTEMS
225 static unsigned get_HZ_by_waiting(void)
227 struct timeval tv1, tv2;
228 unsigned t1, t2, r, hz;
229 unsigned cnt = cnt; /* for compiler */
234 /* Wait for times() to reach new tick */
239 gettimeofday(&tv2, NULL);
243 tv1.tv_usec = tv2.tv_usec;
245 /* Wait exactly one times() tick */
249 gettimeofday(&tv2, NULL);
251 /* Calculate ticks per sec, rounding up to even */
252 diff = tv2.tv_usec - tv1.tv_usec;
253 if (diff <= 0) diff += 1000000;
254 hz = 1000000u / (unsigned)diff;
257 /* Count how many same hz values we saw */
263 } while (cnt < 3); /* exit if saw 3 same values */
268 static inline unsigned get_HZ_by_waiting(void)
275 static unsigned get_kernel_HZ(void)
280 /* Works for ELF only, Linux 2.4.0+ */
281 kernel_HZ = find_elf_note(AT_CLKTCK);
282 if (kernel_HZ == (unsigned)-1)
283 kernel_HZ = get_HZ_by_waiting();
285 G.seconds_since_boot = get_uptime();
291 /* Print value to buf, max size+1 chars (including trailing '\0') */
293 static void func_user(char *buf, int size, const procps_status_t *ps)
296 safe_strncpy(buf, get_cached_username(ps->uid), size+1);
298 /* "compatible" version, but it's larger */
299 /* procps 2.18 shows numeric UID if name overflows the field */
300 /* TODO: get_cached_username() returns numeric string if
301 * user has no passwd record, we will display it
302 * left-justified here; too long usernames are shown
303 * as _right-justified_ IDs. Is it worth fixing? */
304 const char *user = get_cached_username(ps->uid);
305 if (strlen(user) <= size)
306 safe_strncpy(buf, user, size+1);
308 sprintf(buf, "%*u", size, (unsigned)ps->uid);
312 static void func_group(char *buf, int size, const procps_status_t *ps)
314 safe_strncpy(buf, get_cached_groupname(ps->gid), size+1);
317 static void func_comm(char *buf, int size, const procps_status_t *ps)
319 safe_strncpy(buf, ps->comm, size+1);
322 static void func_state(char *buf, int size, const procps_status_t *ps)
324 safe_strncpy(buf, ps->state, size+1);
327 static void func_args(char *buf, int size, const procps_status_t *ps)
329 read_cmdline(buf, size+1, ps->pid, ps->comm);
332 static void func_pid(char *buf, int size, const procps_status_t *ps)
334 sprintf(buf, "%*u", size, ps->pid);
337 static void func_ppid(char *buf, int size, const procps_status_t *ps)
339 sprintf(buf, "%*u", size, ps->ppid);
342 static void func_pgid(char *buf, int size, const procps_status_t *ps)
344 sprintf(buf, "%*u", size, ps->pgid);
347 static void put_lu(char *buf, int size, unsigned long u)
351 /* see http://en.wikipedia.org/wiki/Tera */
352 smart_ulltoa4(u, buf4, " mgtpezy")[0] = '\0';
353 sprintf(buf, "%.*s", size, buf4);
356 static void func_vsz(char *buf, int size, const procps_status_t *ps)
358 put_lu(buf, size, ps->vsz);
361 static void func_rss(char *buf, int size, const procps_status_t *ps)
363 put_lu(buf, size, ps->rss);
366 static void func_tty(char *buf, int size, const procps_status_t *ps)
370 if (ps->tty_major) /* tty field of "0" means "no tty" */
371 snprintf(buf, size+1, "%u,%u", ps->tty_major, ps->tty_minor);
374 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
376 static void func_rgroup(char *buf, int size, const procps_status_t *ps)
378 safe_strncpy(buf, get_cached_groupname(ps->rgid), size+1);
381 static void func_ruser(char *buf, int size, const procps_status_t *ps)
383 safe_strncpy(buf, get_cached_username(ps->ruid), size+1);
386 static void func_nice(char *buf, int size, const procps_status_t *ps)
388 sprintf(buf, "%*d", size, ps->niceness);
393 #if ENABLE_FEATURE_PS_TIME
395 static void func_etime(char *buf, int size, const procps_status_t *ps)
397 /* elapsed time [[dd-]hh:]mm:ss; here only mm:ss */
401 mm = ps->start_time / get_kernel_HZ();
402 /* must be after get_kernel_HZ()! */
403 mm = G.seconds_since_boot - mm;
406 snprintf(buf, size+1, "%3lu:%02u", mm, ss);
409 static void func_time(char *buf, int size, const procps_status_t *ps)
411 /* cumulative time [[dd-]hh:]mm:ss; here only mm:ss */
415 mm = (ps->utime + ps->stime) / get_kernel_HZ();
418 snprintf(buf, size+1, "%3lu:%02u", mm, ss);
424 static void func_label(char *buf, int size, const procps_status_t *ps)
426 safe_strncpy(buf, ps->context ? ps->context : "unknown", size+1);
431 static void func_nice(char *buf, int size, const procps_status_t *ps)
436 static void func_pcpu(char *buf, int size, const procps_status_t *ps)
441 static const ps_out_t out_spec[] = {
442 /* Mandated by http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html: */
443 { 8 , "user" ,"USER" ,func_user ,PSSCAN_UIDGID },
444 { 8 , "group" ,"GROUP" ,func_group ,PSSCAN_UIDGID },
445 { 16 , "comm" ,"COMMAND",func_comm ,PSSCAN_COMM },
446 { MAX_WIDTH , "args" ,"COMMAND",func_args ,PSSCAN_COMM },
447 { 5 , "pid" ,"PID" ,func_pid ,PSSCAN_PID },
448 { 5 , "ppid" ,"PPID" ,func_ppid ,PSSCAN_PPID },
449 { 5 , "pgid" ,"PGID" ,func_pgid ,PSSCAN_PGID },
450 #if ENABLE_FEATURE_PS_TIME
451 { sizeof("ELAPSED")-1, "etime" ,"ELAPSED",func_etime ,PSSCAN_START_TIME },
453 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
454 { 5 , "nice" ,"NI" ,func_nice ,PSSCAN_NICE },
455 { 8 , "rgroup","RGROUP" ,func_rgroup,PSSCAN_RUIDGID },
456 { 8 , "ruser" ,"RUSER" ,func_ruser ,PSSCAN_RUIDGID },
457 // { 5 , "pcpu" ,"%CPU" ,func_pcpu ,PSSCAN_ },
459 #if ENABLE_FEATURE_PS_TIME
460 { 6 , "time" ,"TIME" ,func_time ,PSSCAN_STIME | PSSCAN_UTIME },
462 { 6 , "tty" ,"TT" ,func_tty ,PSSCAN_TTY },
463 { 4 , "vsz" ,"VSZ" ,func_vsz ,PSSCAN_VSZ },
464 /* Not mandated, but useful: */
465 { 4 , "stat" ,"STAT" ,func_state ,PSSCAN_STATE },
466 { 4 , "rss" ,"RSS" ,func_rss ,PSSCAN_RSS },
468 { 35 , "label" ,"LABEL" ,func_label ,PSSCAN_CONTEXT },
472 static ps_out_t* new_out_t(void)
474 out = xrealloc_vector(out, 2, out_cnt);
475 return &out[out_cnt++];
478 static const ps_out_t* find_out_spec(const char *name)
481 char buf[ARRAY_SIZE(out_spec)*7 + 1];
484 for (i = 0; i < ARRAY_SIZE(out_spec); i++) {
485 if (strncmp(name, out_spec[i].name6, 6) == 0)
487 p += sprintf(p, "%.6s,", out_spec[i].name6);
490 bb_error_msg_and_die("bad -o argument '%s', supported arguments: %s", name, buf);
493 static void parse_o(char* opt)
496 // POSIX: "-o is blank- or comma-separated list" (FIXME)
499 comma = strchr(opt, ',');
500 equal = strchr(opt, '=');
501 if (comma && (!equal || equal > comma)) {
503 *new_out_t() = *find_out_spec(opt);
510 // opt points to last spec in comma separated list.
511 // This one can have =HEADER part.
515 *new = *find_out_spec(opt);
518 new->header = equal + 1;
519 // POSIX: the field widths shall be ... at least as wide as
520 // the header text (default or overridden value).
521 // If the header text is null, such as -o user=,
522 // the field width shall be at least as wide as the
523 // default header text
524 if (new->header[0]) {
525 new->width = strlen(new->header);
532 static void alloc_line_buffer(void)
536 for (i = 0; i < out_cnt; i++) {
537 need_flags |= out[i].ps_flags;
538 if (out[i].header[0]) {
541 width += out[i].width + 1; /* "FIELD " */
542 if ((int)(width - terminal_width) > 0) {
543 /* The rest does not fit on the screen */
544 //out[i].width -= (width - terminal_width - 1);
550 if (!is_selinux_enabled())
551 need_flags &= ~PSSCAN_CONTEXT;
553 buffer = xmalloc(width + 1); /* for trailing \0 */
556 static void format_header(void)
569 if (++i == out_cnt) /* do not pad last field */
571 p += sprintf(p, "%-*s ", op->width, op->header);
573 strcpy(p, op->header);
575 printf("%.*s\n", terminal_width, buffer);
578 static void format_process(const procps_status_t *ps)
583 if (out_cnt) while (1) {
584 out[i].f(p, out[i].width, ps);
585 // POSIX: Any field need not be meaningful in all
586 // implementations. In such a case a hyphen ( '-' )
587 // should be output in place of the field value.
594 len = out[i].width - len + 1;
595 if (++i == out_cnt) /* do not pad last field */
597 p += sprintf(p, "%*s", len, "");
599 printf("%.*s\n", terminal_width, buffer);
603 # define SELINUX_O_PREFIX "label,"
604 # define DEFAULT_O_STR (SELINUX_O_PREFIX "pid,user" IF_FEATURE_PS_TIME(",time") ",args")
606 # define DEFAULT_O_STR ("pid,user" IF_FEATURE_PS_TIME(",time") ",args")
609 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
610 int ps_main(int argc UNUSED_PARAM, char **argv)
613 llist_t* opt_o = NULL;
614 char default_o[sizeof(DEFAULT_O_STR)];
625 OPT_T = (1 << 8) * ENABLE_FEATURE_SHOW_THREADS,
631 // -a Write information for all processes associated with terminals
632 // Implementations may omit session leaders from this list
633 // -A Write information for all processes
634 // -d Write information for all processes, except session leaders
635 // -e Write information for all processes (equivalent to -A)
636 // -f Generate a full listing
637 // -l Generate a long listing
638 // -o col1,col2,col3=header
639 // Select which columns to display
640 /* We allow (and ignore) most of the above. FIXME.
641 * -T is picked for threads (POSIX hasn't standardized it).
642 * procps v3.2.7 supports -T and shows tids as SPID column,
643 * it also supports -L where it shows tids as LWP column.
645 opt = getopt32(argv, "Zo:*aAdefl"IF_FEATURE_SHOW_THREADS("T"), &opt_o);
648 parse_o(llist_pop(&opt_o));
651 /* Below: parse_o() needs char*, NOT const char*,
652 * can't pass it constant string. Need to make a copy first.
655 if (!(opt & OPT_Z) || !is_selinux_enabled()) {
656 /* no -Z or no SELinux: do not show LABEL */
657 strcpy(default_o, DEFAULT_O_STR + sizeof(SELINUX_O_PREFIX)-1);
661 strcpy(default_o, DEFAULT_O_STR);
665 #if ENABLE_FEATURE_SHOW_THREADS
667 need_flags |= PSSCAN_TASKS;
670 /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
671 * and such large widths */
672 terminal_width = MAX_WIDTH;
674 terminal_width = get_terminal_width(0);
675 if (--terminal_width > MAX_WIDTH)
676 terminal_width = MAX_WIDTH;
682 while ((p = procps_scan(p, need_flags)) != NULL) {
690 #else /* !ENABLE_DESKTOP */
693 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
694 int ps_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
697 int psscan_flags = PSSCAN_PID | PSSCAN_UIDGID
698 | PSSCAN_STATE | PSSCAN_VSZ | PSSCAN_COMM;
699 unsigned terminal_width IF_NOT_FEATURE_PS_WIDE(= 79);
701 OPT_Z = (1 << 0) * ENABLE_SELINUX,
702 OPT_T = (1 << ENABLE_SELINUX) * ENABLE_FEATURE_SHOW_THREADS,
703 OPT_l = (1 << ENABLE_SELINUX) * (1 << ENABLE_FEATURE_SHOW_THREADS) * ENABLE_FEATURE_PS_LONG,
705 #if ENABLE_FEATURE_PS_LONG
706 time_t now = now; /* for compiler */
707 unsigned long uptime = uptime;
709 /* If we support any options, parse argv */
710 #if ENABLE_SELINUX || ENABLE_FEATURE_SHOW_THREADS || ENABLE_FEATURE_PS_WIDE || ENABLE_FEATURE_PS_LONG
712 # if ENABLE_FEATURE_PS_WIDE
713 /* -w is a bit complicated */
715 opt_complementary = "-:ww";
716 opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T")IF_FEATURE_PS_LONG("l")
718 /* if w is given once, GNU ps sets the width to 132,
719 * if w is given more than once, it is "unlimited"
722 terminal_width = (w_count == 1) ? 132 : MAX_WIDTH;
724 terminal_width = get_terminal_width(0);
726 if (--terminal_width > MAX_WIDTH)
727 terminal_width = MAX_WIDTH;
730 /* -w is not supported, only -Z and/or -T */
731 opt_complementary = "-";
732 opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T")IF_FEATURE_PS_LONG("l"));
736 if ((opts & OPT_Z) && is_selinux_enabled()) {
737 psscan_flags = PSSCAN_PID | PSSCAN_CONTEXT
738 | PSSCAN_STATE | PSSCAN_COMM;
739 puts(" PID CONTEXT STAT COMMAND");
743 psscan_flags = PSSCAN_STATE | PSSCAN_UIDGID | PSSCAN_PID | PSSCAN_PPID
744 | PSSCAN_TTY | PSSCAN_STIME | PSSCAN_UTIME | PSSCAN_COMM
745 | PSSCAN_VSZ | PSSCAN_RSS;
746 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
752 * -PRI The priority of the process; higher numbers mean lower priority
754 * -ADDR The address of the process (?)
755 * SZ The size in blocks of the core image
756 * -WCHAN The event for which the process is waiting or sleeping
758 * TIME The cumulative execution time
760 * We don't show fields marked with '-'.
761 * We show VSZ and RSS instead of SZ.
762 * We also show STIME (standard says that -f shows it, -l doesn't).
764 puts("S UID PID PPID VSZ RSS TTY STIME TIME CMD");
765 # if ENABLE_FEATURE_PS_LONG
767 uptime = get_uptime();
771 puts(" PID USER VSZ STAT COMMAND");
774 psscan_flags |= PSSCAN_TASKS;
779 while ((p = procps_scan(p, psscan_flags)) != NULL) {
782 if (psscan_flags & PSSCAN_CONTEXT) {
783 len = printf("%5u %-32.32s %s ",
785 p->context ? p->context : "unknown",
791 smart_ulltoa5(p->vsz, buf6, " mgtpezy")[0] = '\0';
792 #if ENABLE_FEATURE_PS_LONG
794 char bufr[6], stime_str[6];
795 char tty[2 * sizeof(int)*3 + 2];
797 unsigned sut = (p->stime + p->utime) / 100;
798 unsigned elapsed = uptime - (p->start_time / 100);
799 time_t start = now - elapsed;
800 struct tm *tm = localtime(&start);
802 smart_ulltoa5(p->rss, bufr, " mgtpezy")[0] = '\0';
804 if (p->tty_major == 136)
805 /* It should be pts/N, not ptsN, but N > 9
806 * will overflow field width...
808 endp = stpcpy(tty, "pts");
810 if (p->tty_major == 4) {
811 endp = stpcpy(tty, "tty");
812 if (p->tty_minor >= 64) {
818 endp = tty + sprintf(tty, "%d:", p->tty_major);
819 strcpy(endp, utoa(p->tty_minor));
821 strftime(stime_str, 6, (elapsed >= (24 * 60 * 60)) ? "%b%d" : "%H:%M", tm);
823 // S UID PID PPID VSZ RSS TTY STIME TIME CMD
824 len = printf("%c %5u %5u %5u %5s %5s %-5s %s %02u:%02u:%02u ",
825 p->state[0], p->uid, p->pid, p->ppid, buf6, bufr, tty,
826 stime_str, sut / 3600, (sut % 3600) / 60, sut % 60);
830 const char *user = get_cached_username(p->uid);
831 len = printf("%5u %-8.8s %s %s ",
832 p->pid, user, buf6, p->state);
837 int sz = terminal_width - len;
840 read_cmdline(buf, sz, p->pid, p->comm);
845 if (ENABLE_FEATURE_CLEAN_UP)
846 clear_username_cache();
850 #endif /* !ENABLE_DESKTOP */