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"
43 //usage:#endif /* ENABLE_DESKTOP */
45 //usage:#define ps_example_usage
47 //usage: " PID Uid Gid State Command\n"
48 //usage: " 1 root root S init\n"
49 //usage: " 2 root root S [kflushd]\n"
50 //usage: " 3 root root S [kupdate]\n"
51 //usage: " 4 root root S [kpiod]\n"
52 //usage: " 5 root root S [kswapd]\n"
53 //usage: " 742 andersen andersen S [bash]\n"
54 //usage: " 743 andersen andersen S -bash\n"
55 //usage: " 745 root root S [getty]\n"
56 //usage: " 2990 andersen andersen R ps\n"
60 /* Absolute maximum on output line length */
61 enum { MAX_WIDTH = 2*1024 };
66 # include <sys/sysinfo.h>
68 #include <sys/times.h> /* for times() */
74 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
75 * specifies (for XSI-conformant systems) following default columns
76 * (l and f mark columns shown with -l and -f respectively):
77 * F l Flags (octal and additive) associated with the process (??)
78 * S l The state of the process
79 * UID f,l The user ID; the login name is printed with -f
81 * PPID f,l The parent process
82 * C f,l Processor utilization
83 * PRI l The priority of the process; higher numbers mean lower priority
85 * ADDR l The address of the process
86 * SZ l The size in blocks of the core image of the process
87 * WCHAN l The event for which the process is waiting or sleeping
88 * STIME f Starting time of the process
89 * TTY The controlling terminal for the process
90 * TIME The cumulative execution time for the process
91 * CMD The command name; the full command line is shown with -f
97 void (*f)(char *buf, int size, const procps_status_t *ps);
107 unsigned terminal_width;
108 #if ENABLE_FEATURE_PS_TIME
110 unsigned long long seconds_since_boot;
113 #define G (*(struct globals*)&bb_common_bufsiz1)
115 #define out_cnt (G.out_cnt )
116 #define print_header (G.print_header )
117 #define need_flags (G.need_flags )
118 #define buffer (G.buffer )
119 #define terminal_width (G.terminal_width )
120 #define kernel_HZ (G.kernel_HZ )
121 #define seconds_since_boot (G.seconds_since_boot)
122 #define INIT_G() do { } while (0)
124 #if ENABLE_FEATURE_PS_TIME
125 /* for ELF executables, notes are pushed before environment and args */
126 static ptrdiff_t find_elf_note(ptrdiff_t findme)
128 ptrdiff_t *ep = (ptrdiff_t *) environ;
133 if (ep[0] == findme) {
141 #if ENABLE_FEATURE_PS_UNUSUAL_SYSTEMS
142 static unsigned get_HZ_by_waiting(void)
144 struct timeval tv1, tv2;
145 unsigned t1, t2, r, hz;
146 unsigned cnt = cnt; /* for compiler */
151 /* Wait for times() to reach new tick */
156 gettimeofday(&tv2, NULL);
160 tv1.tv_usec = tv2.tv_usec;
162 /* Wait exactly one times() tick */
166 gettimeofday(&tv2, NULL);
168 /* Calculate ticks per sec, rounding up to even */
169 diff = tv2.tv_usec - tv1.tv_usec;
170 if (diff <= 0) diff += 1000000;
171 hz = 1000000u / (unsigned)diff;
174 /* Count how many same hz values we saw */
180 } while (cnt < 3); /* exit if saw 3 same values */
185 static inline unsigned get_HZ_by_waiting(void)
192 static unsigned get_kernel_HZ(void)
200 /* Works for ELF only, Linux 2.4.0+ */
201 kernel_HZ = find_elf_note(AT_CLKTCK);
202 if (kernel_HZ == (unsigned)-1)
203 kernel_HZ = get_HZ_by_waiting();
205 //if (open_read_close("/proc/uptime", buf, sizeof(buf)) <= 0)
206 // bb_perror_msg_and_die("can't read %s", "/proc/uptime");
207 //buf[sizeof(buf)-1] = '\0';
208 ///sscanf(buf, "%llu", &seconds_since_boot);
210 seconds_since_boot = info.uptime;
216 /* Print value to buf, max size+1 chars (including trailing '\0') */
218 static void func_user(char *buf, int size, const procps_status_t *ps)
221 safe_strncpy(buf, get_cached_username(ps->uid), size+1);
223 /* "compatible" version, but it's larger */
224 /* procps 2.18 shows numeric UID if name overflows the field */
225 /* TODO: get_cached_username() returns numeric string if
226 * user has no passwd record, we will display it
227 * left-justified here; too long usernames are shown
228 * as _right-justified_ IDs. Is it worth fixing? */
229 const char *user = get_cached_username(ps->uid);
230 if (strlen(user) <= size)
231 safe_strncpy(buf, user, size+1);
233 sprintf(buf, "%*u", size, (unsigned)ps->uid);
237 static void func_group(char *buf, int size, const procps_status_t *ps)
239 safe_strncpy(buf, get_cached_groupname(ps->gid), size+1);
242 static void func_comm(char *buf, int size, const procps_status_t *ps)
244 safe_strncpy(buf, ps->comm, size+1);
247 static void func_state(char *buf, int size, const procps_status_t *ps)
249 safe_strncpy(buf, ps->state, size+1);
252 static void func_args(char *buf, int size, const procps_status_t *ps)
254 read_cmdline(buf, size+1, ps->pid, ps->comm);
257 static void func_pid(char *buf, int size, const procps_status_t *ps)
259 sprintf(buf, "%*u", size, ps->pid);
262 static void func_ppid(char *buf, int size, const procps_status_t *ps)
264 sprintf(buf, "%*u", size, ps->ppid);
267 static void func_pgid(char *buf, int size, const procps_status_t *ps)
269 sprintf(buf, "%*u", size, ps->pgid);
272 static void put_lu(char *buf, int size, unsigned long u)
276 /* see http://en.wikipedia.org/wiki/Tera */
277 smart_ulltoa4(u, buf4, " mgtpezy");
279 sprintf(buf, "%.*s", size, buf4);
282 static void func_vsz(char *buf, int size, const procps_status_t *ps)
284 put_lu(buf, size, ps->vsz);
287 static void func_rss(char *buf, int size, const procps_status_t *ps)
289 put_lu(buf, size, ps->rss);
292 static void func_tty(char *buf, int size, const procps_status_t *ps)
296 if (ps->tty_major) /* tty field of "0" means "no tty" */
297 snprintf(buf, size+1, "%u,%u", ps->tty_major, ps->tty_minor);
300 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
302 static void func_rgroup(char *buf, int size, const procps_status_t *ps)
304 safe_strncpy(buf, get_cached_groupname(ps->rgid), size+1);
307 static void func_ruser(char *buf, int size, const procps_status_t *ps)
309 safe_strncpy(buf, get_cached_username(ps->ruid), size+1);
312 static void func_nice(char *buf, int size, const procps_status_t *ps)
314 sprintf(buf, "%*d", size, ps->niceness);
319 #if ENABLE_FEATURE_PS_TIME
321 static void func_etime(char *buf, int size, const procps_status_t *ps)
323 /* elapsed time [[dd-]hh:]mm:ss; here only mm:ss */
327 mm = ps->start_time / get_kernel_HZ();
328 /* must be after get_kernel_HZ()! */
329 mm = seconds_since_boot - mm;
332 snprintf(buf, size+1, "%3lu:%02u", mm, ss);
335 static void func_time(char *buf, int size, const procps_status_t *ps)
337 /* cumulative time [[dd-]hh:]mm:ss; here only mm:ss */
341 mm = (ps->utime + ps->stime) / get_kernel_HZ();
344 snprintf(buf, size+1, "%3lu:%02u", mm, ss);
350 static void func_label(char *buf, int size, const procps_status_t *ps)
352 safe_strncpy(buf, ps->context ? ps->context : "unknown", size+1);
357 static void func_nice(char *buf, int size, const procps_status_t *ps)
362 static void func_pcpu(char *buf, int size, const procps_status_t *ps)
367 static const ps_out_t out_spec[] = {
368 /* Mandated by http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html: */
369 { 8 , "user" ,"USER" ,func_user ,PSSCAN_UIDGID },
370 { 8 , "group" ,"GROUP" ,func_group ,PSSCAN_UIDGID },
371 { 16 , "comm" ,"COMMAND",func_comm ,PSSCAN_COMM },
372 { MAX_WIDTH , "args" ,"COMMAND",func_args ,PSSCAN_COMM },
373 { 5 , "pid" ,"PID" ,func_pid ,PSSCAN_PID },
374 { 5 , "ppid" ,"PPID" ,func_ppid ,PSSCAN_PPID },
375 { 5 , "pgid" ,"PGID" ,func_pgid ,PSSCAN_PGID },
376 #if ENABLE_FEATURE_PS_TIME
377 { sizeof("ELAPSED")-1, "etime" ,"ELAPSED",func_etime ,PSSCAN_START_TIME },
379 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
380 { 5 , "nice" ,"NI" ,func_nice ,PSSCAN_NICE },
381 { 8 , "rgroup","RGROUP" ,func_rgroup,PSSCAN_RUIDGID },
382 { 8 , "ruser" ,"RUSER" ,func_ruser ,PSSCAN_RUIDGID },
383 // { 5 , "pcpu" ,"%CPU" ,func_pcpu ,PSSCAN_ },
385 #if ENABLE_FEATURE_PS_TIME
386 { 6 , "time" ,"TIME" ,func_time ,PSSCAN_STIME | PSSCAN_UTIME },
388 { 6 , "tty" ,"TT" ,func_tty ,PSSCAN_TTY },
389 { 4 , "vsz" ,"VSZ" ,func_vsz ,PSSCAN_VSZ },
390 /* Not mandated, but useful: */
391 { 4 , "stat" ,"STAT" ,func_state ,PSSCAN_STATE },
392 { 4 , "rss" ,"RSS" ,func_rss ,PSSCAN_RSS },
394 { 35 , "label" ,"LABEL" ,func_label ,PSSCAN_CONTEXT },
398 static ps_out_t* new_out_t(void)
400 out = xrealloc_vector(out, 2, out_cnt);
401 return &out[out_cnt++];
404 static const ps_out_t* find_out_spec(const char *name)
407 char buf[ARRAY_SIZE(out_spec)*7 + 1];
410 for (i = 0; i < ARRAY_SIZE(out_spec); i++) {
411 if (strncmp(name, out_spec[i].name6, 6) == 0)
413 p += sprintf(p, "%.6s,", out_spec[i].name6);
416 bb_error_msg_and_die("bad -o argument '%s', supported arguments: %s", name, buf);
419 static void parse_o(char* opt)
422 // POSIX: "-o is blank- or comma-separated list" (FIXME)
425 comma = strchr(opt, ',');
426 equal = strchr(opt, '=');
427 if (comma && (!equal || equal > comma)) {
429 *new_out_t() = *find_out_spec(opt);
436 // opt points to last spec in comma separated list.
437 // This one can have =HEADER part.
441 *new = *find_out_spec(opt);
444 new->header = equal + 1;
445 // POSIX: the field widths shall be ... at least as wide as
446 // the header text (default or overridden value).
447 // If the header text is null, such as -o user=,
448 // the field width shall be at least as wide as the
449 // default header text
450 if (new->header[0]) {
451 new->width = strlen(new->header);
458 static void alloc_line_buffer(void)
462 for (i = 0; i < out_cnt; i++) {
463 need_flags |= out[i].ps_flags;
464 if (out[i].header[0]) {
467 width += out[i].width + 1; /* "FIELD " */
468 if ((int)(width - terminal_width) > 0) {
469 /* The rest does not fit on the screen */
470 //out[i].width -= (width - terminal_width - 1);
476 if (!is_selinux_enabled())
477 need_flags &= ~PSSCAN_CONTEXT;
479 buffer = xmalloc(width + 1); /* for trailing \0 */
482 static void format_header(void)
495 if (++i == out_cnt) /* do not pad last field */
497 p += sprintf(p, "%-*s ", op->width, op->header);
499 strcpy(p, op->header);
501 printf("%.*s\n", terminal_width, buffer);
504 static void format_process(const procps_status_t *ps)
509 if (out_cnt) while (1) {
510 out[i].f(p, out[i].width, ps);
511 // POSIX: Any field need not be meaningful in all
512 // implementations. In such a case a hyphen ( '-' )
513 // should be output in place of the field value.
520 len = out[i].width - len + 1;
521 if (++i == out_cnt) /* do not pad last field */
523 p += sprintf(p, "%*s", len, "");
525 printf("%.*s\n", terminal_width, buffer);
529 # define SELINUX_O_PREFIX "label,"
530 # define DEFAULT_O_STR (SELINUX_O_PREFIX "pid,user" IF_FEATURE_PS_TIME(",time") ",args")
532 # define DEFAULT_O_STR ("pid,user" IF_FEATURE_PS_TIME(",time") ",args")
535 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
536 int ps_main(int argc UNUSED_PARAM, char **argv)
539 llist_t* opt_o = NULL;
540 char default_o[sizeof(DEFAULT_O_STR)];
551 OPT_T = (1 << 8) * ENABLE_FEATURE_SHOW_THREADS,
557 // -a Write information for all processes associated with terminals
558 // Implementations may omit session leaders from this list
559 // -A Write information for all processes
560 // -d Write information for all processes, except session leaders
561 // -e Write information for all processes (equivalent to -A)
562 // -f Generate a full listing
563 // -l Generate a long listing
564 // -o col1,col2,col3=header
565 // Select which columns to display
566 /* We allow (and ignore) most of the above. FIXME.
567 * -T is picked for threads (POSIX hasn't it standardized).
568 * procps v3.2.7 supports -T and shows tids as SPID column,
569 * it also supports -L where it shows tids as LWP column.
571 opt_complementary = "o::";
572 opt = getopt32(argv, "Zo:aAdefl"IF_FEATURE_SHOW_THREADS("T"), &opt_o);
575 parse_o(llist_pop(&opt_o));
578 /* Below: parse_o() needs char*, NOT const char*, can't give it default_o */
580 if (!(opt & OPT_Z) || !is_selinux_enabled()) {
581 /* no -Z or no SELinux: do not show LABEL */
582 strcpy(default_o, DEFAULT_O_STR + sizeof(SELINUX_O_PREFIX)-1);
586 strcpy(default_o, DEFAULT_O_STR);
590 #if ENABLE_FEATURE_SHOW_THREADS
592 need_flags |= PSSCAN_TASKS;
595 /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
596 * and such large widths */
597 terminal_width = MAX_WIDTH;
599 get_terminal_width_height(0, &terminal_width, NULL);
600 if (--terminal_width > MAX_WIDTH)
601 terminal_width = MAX_WIDTH;
607 while ((p = procps_scan(p, need_flags)) != NULL) {
615 #else /* !ENABLE_DESKTOP */
618 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
619 int ps_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
622 int psscan_flags = PSSCAN_PID | PSSCAN_UIDGID
623 | PSSCAN_STATE | PSSCAN_VSZ | PSSCAN_COMM;
624 unsigned terminal_width IF_NOT_FEATURE_PS_WIDE(= 79);
626 OPT_Z = (1 << 0) * ENABLE_SELINUX,
627 OPT_T = (1 << ENABLE_SELINUX) * ENABLE_FEATURE_SHOW_THREADS,
630 /* If we support any options, parse argv */
631 #if ENABLE_SELINUX || ENABLE_FEATURE_SHOW_THREADS || ENABLE_FEATURE_PS_WIDE
632 # if ENABLE_FEATURE_PS_WIDE
633 /* -w is a bit complicated */
635 opt_complementary = "-:ww";
636 opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T")"w", &w_count);
637 /* if w is given once, GNU ps sets the width to 132,
638 * if w is given more than once, it is "unlimited"
641 terminal_width = (w_count == 1) ? 132 : MAX_WIDTH;
643 get_terminal_width_height(0, &terminal_width, NULL);
645 if (--terminal_width > MAX_WIDTH)
646 terminal_width = MAX_WIDTH;
649 /* -w is not supported, only -Z and/or -T */
650 opt_complementary = "-";
651 opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T"));
656 if ((opts & OPT_Z) && is_selinux_enabled()) {
657 psscan_flags = PSSCAN_PID | PSSCAN_CONTEXT
658 | PSSCAN_STATE | PSSCAN_COMM;
659 puts(" PID CONTEXT STAT COMMAND");
663 puts(" PID USER VSZ STAT COMMAND");
666 psscan_flags |= PSSCAN_TASKS;
670 while ((p = procps_scan(p, psscan_flags)) != NULL) {
673 if (psscan_flags & PSSCAN_CONTEXT) {
674 len = printf("%5u %-32.32s %s ",
676 p->context ? p->context : "unknown",
681 const char *user = get_cached_username(p->uid);
683 // len = printf("%5u %-8.8s %s ",
684 // p->pid, user, p->state);
688 smart_ulltoa5(p->vsz, buf6, " mgtpezy");
690 len = printf("%5u %-8.8s %s %s ",
691 p->pid, user, buf6, p->state);
696 int sz = terminal_width - len;
698 read_cmdline(buf, sz, p->pid, p->comm);
702 if (ENABLE_FEATURE_CLEAN_UP)
703 clear_username_cache();
707 #endif /* !ENABLE_DESKTOP */