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"
66 # include <sys/sysinfo.h>
69 /* Absolute maximum on output line length */
70 enum { MAX_WIDTH
= 2*1024 };
72 #if ENABLE_FEATURE_PS_TIME || ENABLE_FEATURE_PS_LONG
73 static long get_uptime(void)
77 if (sysinfo(&info
) < 0)
83 if (open_read_close("/proc/uptime", buf
, sizeof(buf
)) <= 0)
84 bb_perror_msg_and_die("can't read %s", "/proc/uptime");
85 buf
[sizeof(buf
)-1] = '\0';
86 sscanf(buf
, "%l", &uptime
);
90 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) < 0)
99 #include <sys/times.h> /* for times() */
101 # define AT_CLKTCK 17
105 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
106 * specifies (for XSI-conformant systems) following default columns
107 * (l and f mark columns shown with -l and -f respectively):
108 * F l Flags (octal and additive) associated with the process (??)
109 * S l The state of the process
110 * UID f,l The user ID; the login name is printed with -f
112 * PPID f,l The parent process
113 * C f,l Processor utilization
114 * PRI l The priority of the process; higher numbers mean lower priority
116 * ADDR l The address of the process
117 * SZ l The size in blocks of the core image of the process
118 * WCHAN l The event for which the process is waiting or sleeping
119 * STIME f Starting time of the process
120 * TTY The controlling terminal for the process
121 * TIME The cumulative execution time for the process
122 * CMD The command name; the full command line is shown with -f
128 void (*f
)(char *buf
, int size
, const procps_status_t
*ps
);
138 unsigned terminal_width
;
139 #if ENABLE_FEATURE_PS_TIME
141 unsigned long long seconds_since_boot
;
144 #define G (*(struct globals*)&bb_common_bufsiz1)
146 #define out_cnt (G.out_cnt )
147 #define print_header (G.print_header )
148 #define need_flags (G.need_flags )
149 #define buffer (G.buffer )
150 #define terminal_width (G.terminal_width )
151 #define kernel_HZ (G.kernel_HZ )
152 #define seconds_since_boot (G.seconds_since_boot)
153 #define INIT_G() do { } while (0)
155 #if ENABLE_FEATURE_PS_TIME
156 /* for ELF executables, notes are pushed before environment and args */
157 static ptrdiff_t find_elf_note(ptrdiff_t findme
)
159 ptrdiff_t *ep
= (ptrdiff_t *) environ
;
164 if (ep
[0] == findme
) {
172 #if ENABLE_FEATURE_PS_UNUSUAL_SYSTEMS
173 static unsigned get_HZ_by_waiting(void)
175 struct timeval tv1
, tv2
;
176 unsigned t1
, t2
, r
, hz
;
177 unsigned cnt
= cnt
; /* for compiler */
182 /* Wait for times() to reach new tick */
187 gettimeofday(&tv2
, NULL
);
191 tv1
.tv_usec
= tv2
.tv_usec
;
193 /* Wait exactly one times() tick */
197 gettimeofday(&tv2
, NULL
);
199 /* Calculate ticks per sec, rounding up to even */
200 diff
= tv2
.tv_usec
- tv1
.tv_usec
;
201 if (diff
<= 0) diff
+= 1000000;
202 hz
= 1000000u / (unsigned)diff
;
205 /* Count how many same hz values we saw */
211 } while (cnt
< 3); /* exit if saw 3 same values */
216 static inline unsigned get_HZ_by_waiting(void)
223 static unsigned get_kernel_HZ(void)
229 /* Works for ELF only, Linux 2.4.0+ */
230 kernel_HZ
= find_elf_note(AT_CLKTCK
);
231 if (kernel_HZ
== (unsigned)-1)
232 kernel_HZ
= get_HZ_by_waiting();
234 seconds_since_boot
= get_uptime();
240 /* Print value to buf, max size+1 chars (including trailing '\0') */
242 static void func_user(char *buf
, int size
, const procps_status_t
*ps
)
245 safe_strncpy(buf
, get_cached_username(ps
->uid
), size
+1);
247 /* "compatible" version, but it's larger */
248 /* procps 2.18 shows numeric UID if name overflows the field */
249 /* TODO: get_cached_username() returns numeric string if
250 * user has no passwd record, we will display it
251 * left-justified here; too long usernames are shown
252 * as _right-justified_ IDs. Is it worth fixing? */
253 const char *user
= get_cached_username(ps
->uid
);
254 if (strlen(user
) <= size
)
255 safe_strncpy(buf
, user
, size
+1);
257 sprintf(buf
, "%*u", size
, (unsigned)ps
->uid
);
261 static void func_group(char *buf
, int size
, const procps_status_t
*ps
)
263 safe_strncpy(buf
, get_cached_groupname(ps
->gid
), size
+1);
266 static void func_comm(char *buf
, int size
, const procps_status_t
*ps
)
268 safe_strncpy(buf
, ps
->comm
, size
+1);
271 static void func_state(char *buf
, int size
, const procps_status_t
*ps
)
273 safe_strncpy(buf
, ps
->state
, size
+1);
276 static void func_args(char *buf
, int size
, const procps_status_t
*ps
)
278 read_cmdline(buf
, size
+1, ps
->pid
, ps
->comm
);
281 static void func_pid(char *buf
, int size
, const procps_status_t
*ps
)
283 sprintf(buf
, "%*u", size
, ps
->pid
);
286 static void func_ppid(char *buf
, int size
, const procps_status_t
*ps
)
288 sprintf(buf
, "%*u", size
, ps
->ppid
);
291 static void func_pgid(char *buf
, int size
, const procps_status_t
*ps
)
293 sprintf(buf
, "%*u", size
, ps
->pgid
);
296 static void put_lu(char *buf
, int size
, unsigned long u
)
300 /* see http://en.wikipedia.org/wiki/Tera */
301 smart_ulltoa4(u
, buf4
, " mgtpezy");
303 sprintf(buf
, "%.*s", size
, buf4
);
306 static void func_vsz(char *buf
, int size
, const procps_status_t
*ps
)
308 put_lu(buf
, size
, ps
->vsz
);
311 static void func_rss(char *buf
, int size
, const procps_status_t
*ps
)
313 put_lu(buf
, size
, ps
->rss
);
316 static void func_tty(char *buf
, int size
, const procps_status_t
*ps
)
320 if (ps
->tty_major
) /* tty field of "0" means "no tty" */
321 snprintf(buf
, size
+1, "%u,%u", ps
->tty_major
, ps
->tty_minor
);
324 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
326 static void func_rgroup(char *buf
, int size
, const procps_status_t
*ps
)
328 safe_strncpy(buf
, get_cached_groupname(ps
->rgid
), size
+1);
331 static void func_ruser(char *buf
, int size
, const procps_status_t
*ps
)
333 safe_strncpy(buf
, get_cached_username(ps
->ruid
), size
+1);
336 static void func_nice(char *buf
, int size
, const procps_status_t
*ps
)
338 sprintf(buf
, "%*d", size
, ps
->niceness
);
343 #if ENABLE_FEATURE_PS_TIME
345 static void func_etime(char *buf
, int size
, const procps_status_t
*ps
)
347 /* elapsed time [[dd-]hh:]mm:ss; here only mm:ss */
351 mm
= ps
->start_time
/ get_kernel_HZ();
352 /* must be after get_kernel_HZ()! */
353 mm
= seconds_since_boot
- mm
;
356 snprintf(buf
, size
+1, "%3lu:%02u", mm
, ss
);
359 static void func_time(char *buf
, int size
, const procps_status_t
*ps
)
361 /* cumulative time [[dd-]hh:]mm:ss; here only mm:ss */
365 mm
= (ps
->utime
+ ps
->stime
) / get_kernel_HZ();
368 snprintf(buf
, size
+1, "%3lu:%02u", mm
, ss
);
374 static void func_label(char *buf
, int size
, const procps_status_t
*ps
)
376 safe_strncpy(buf
, ps
->context
? ps
->context
: "unknown", size
+1);
381 static void func_nice(char *buf, int size, const procps_status_t *ps)
386 static void func_pcpu(char *buf, int size, const procps_status_t *ps)
391 static const ps_out_t out_spec
[] = {
392 /* Mandated by http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html: */
393 { 8 , "user" ,"USER" ,func_user
,PSSCAN_UIDGID
},
394 { 8 , "group" ,"GROUP" ,func_group
,PSSCAN_UIDGID
},
395 { 16 , "comm" ,"COMMAND",func_comm
,PSSCAN_COMM
},
396 { MAX_WIDTH
, "args" ,"COMMAND",func_args
,PSSCAN_COMM
},
397 { 5 , "pid" ,"PID" ,func_pid
,PSSCAN_PID
},
398 { 5 , "ppid" ,"PPID" ,func_ppid
,PSSCAN_PPID
},
399 { 5 , "pgid" ,"PGID" ,func_pgid
,PSSCAN_PGID
},
400 #if ENABLE_FEATURE_PS_TIME
401 { sizeof("ELAPSED")-1, "etime" ,"ELAPSED",func_etime
,PSSCAN_START_TIME
},
403 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
404 { 5 , "nice" ,"NI" ,func_nice
,PSSCAN_NICE
},
405 { 8 , "rgroup","RGROUP" ,func_rgroup
,PSSCAN_RUIDGID
},
406 { 8 , "ruser" ,"RUSER" ,func_ruser
,PSSCAN_RUIDGID
},
407 // { 5 , "pcpu" ,"%CPU" ,func_pcpu ,PSSCAN_ },
409 #if ENABLE_FEATURE_PS_TIME
410 { 6 , "time" ,"TIME" ,func_time
,PSSCAN_STIME
| PSSCAN_UTIME
},
412 { 6 , "tty" ,"TT" ,func_tty
,PSSCAN_TTY
},
413 { 4 , "vsz" ,"VSZ" ,func_vsz
,PSSCAN_VSZ
},
414 /* Not mandated, but useful: */
415 { 4 , "stat" ,"STAT" ,func_state
,PSSCAN_STATE
},
416 { 4 , "rss" ,"RSS" ,func_rss
,PSSCAN_RSS
},
418 { 35 , "label" ,"LABEL" ,func_label
,PSSCAN_CONTEXT
},
422 static ps_out_t
* new_out_t(void)
424 out
= xrealloc_vector(out
, 2, out_cnt
);
425 return &out
[out_cnt
++];
428 static const ps_out_t
* find_out_spec(const char *name
)
431 char buf
[ARRAY_SIZE(out_spec
)*7 + 1];
434 for (i
= 0; i
< ARRAY_SIZE(out_spec
); i
++) {
435 if (strncmp(name
, out_spec
[i
].name6
, 6) == 0)
437 p
+= sprintf(p
, "%.6s,", out_spec
[i
].name6
);
440 bb_error_msg_and_die("bad -o argument '%s', supported arguments: %s", name
, buf
);
443 static void parse_o(char* opt
)
446 // POSIX: "-o is blank- or comma-separated list" (FIXME)
449 comma
= strchr(opt
, ',');
450 equal
= strchr(opt
, '=');
451 if (comma
&& (!equal
|| equal
> comma
)) {
453 *new_out_t() = *find_out_spec(opt
);
460 // opt points to last spec in comma separated list.
461 // This one can have =HEADER part.
465 *new = *find_out_spec(opt
);
468 new->header
= equal
+ 1;
469 // POSIX: the field widths shall be ... at least as wide as
470 // the header text (default or overridden value).
471 // If the header text is null, such as -o user=,
472 // the field width shall be at least as wide as the
473 // default header text
474 if (new->header
[0]) {
475 new->width
= strlen(new->header
);
482 static void alloc_line_buffer(void)
486 for (i
= 0; i
< out_cnt
; i
++) {
487 need_flags
|= out
[i
].ps_flags
;
488 if (out
[i
].header
[0]) {
491 width
+= out
[i
].width
+ 1; /* "FIELD " */
492 if ((int)(width
- terminal_width
) > 0) {
493 /* The rest does not fit on the screen */
494 //out[i].width -= (width - terminal_width - 1);
500 if (!is_selinux_enabled())
501 need_flags
&= ~PSSCAN_CONTEXT
;
503 buffer
= xmalloc(width
+ 1); /* for trailing \0 */
506 static void format_header(void)
519 if (++i
== out_cnt
) /* do not pad last field */
521 p
+= sprintf(p
, "%-*s ", op
->width
, op
->header
);
523 strcpy(p
, op
->header
);
525 printf("%.*s\n", terminal_width
, buffer
);
528 static void format_process(const procps_status_t
*ps
)
533 if (out_cnt
) while (1) {
534 out
[i
].f(p
, out
[i
].width
, ps
);
535 // POSIX: Any field need not be meaningful in all
536 // implementations. In such a case a hyphen ( '-' )
537 // should be output in place of the field value.
544 len
= out
[i
].width
- len
+ 1;
545 if (++i
== out_cnt
) /* do not pad last field */
547 p
+= sprintf(p
, "%*s", len
, "");
549 printf("%.*s\n", terminal_width
, buffer
);
553 # define SELINUX_O_PREFIX "label,"
554 # define DEFAULT_O_STR (SELINUX_O_PREFIX "pid,user" IF_FEATURE_PS_TIME(",time") ",args")
556 # define DEFAULT_O_STR ("pid,user" IF_FEATURE_PS_TIME(",time") ",args")
559 int ps_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
560 int ps_main(int argc UNUSED_PARAM
, char **argv
)
563 llist_t
* opt_o
= NULL
;
564 char default_o
[sizeof(DEFAULT_O_STR
)];
575 OPT_T
= (1 << 8) * ENABLE_FEATURE_SHOW_THREADS
,
581 // -a Write information for all processes associated with terminals
582 // Implementations may omit session leaders from this list
583 // -A Write information for all processes
584 // -d Write information for all processes, except session leaders
585 // -e Write information for all processes (equivalent to -A)
586 // -f Generate a full listing
587 // -l Generate a long listing
588 // -o col1,col2,col3=header
589 // Select which columns to display
590 /* We allow (and ignore) most of the above. FIXME.
591 * -T is picked for threads (POSIX hasn't it standardized).
592 * procps v3.2.7 supports -T and shows tids as SPID column,
593 * it also supports -L where it shows tids as LWP column.
595 opt_complementary
= "o::";
596 opt
= getopt32(argv
, "Zo:aAdefl"IF_FEATURE_SHOW_THREADS("T"), &opt_o
);
599 parse_o(llist_pop(&opt_o
));
602 /* Below: parse_o() needs char*, NOT const char*, can't give it default_o */
604 if (!(opt
& OPT_Z
) || !is_selinux_enabled()) {
605 /* no -Z or no SELinux: do not show LABEL */
606 strcpy(default_o
, DEFAULT_O_STR
+ sizeof(SELINUX_O_PREFIX
)-1);
610 strcpy(default_o
, DEFAULT_O_STR
);
614 #if ENABLE_FEATURE_SHOW_THREADS
616 need_flags
|= PSSCAN_TASKS
;
619 /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
620 * and such large widths */
621 terminal_width
= MAX_WIDTH
;
623 get_terminal_width_height(0, &terminal_width
, NULL
);
624 if (--terminal_width
> MAX_WIDTH
)
625 terminal_width
= MAX_WIDTH
;
631 while ((p
= procps_scan(p
, need_flags
)) != NULL
) {
639 #else /* !ENABLE_DESKTOP */
642 int ps_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
643 int ps_main(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
646 int psscan_flags
= PSSCAN_PID
| PSSCAN_UIDGID
647 | PSSCAN_STATE
| PSSCAN_VSZ
| PSSCAN_COMM
;
648 unsigned terminal_width
IF_NOT_FEATURE_PS_WIDE(= 79);
650 OPT_Z
= (1 << 0) * ENABLE_SELINUX
,
651 OPT_T
= (1 << ENABLE_SELINUX
) * ENABLE_FEATURE_SHOW_THREADS
,
652 OPT_l
= (1 << ENABLE_SELINUX
) * (1 << ENABLE_FEATURE_SHOW_THREADS
) * ENABLE_FEATURE_PS_LONG
,
654 #if ENABLE_FEATURE_PS_LONG
658 /* If we support any options, parse argv */
659 #if ENABLE_SELINUX || ENABLE_FEATURE_SHOW_THREADS || ENABLE_FEATURE_PS_WIDE || ENABLE_FEATURE_PS_LONG
661 # if ENABLE_FEATURE_PS_WIDE
662 /* -w is a bit complicated */
664 opt_complementary
= "-:ww";
665 opts
= getopt32(argv
, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T")IF_FEATURE_PS_LONG("l")
667 /* if w is given once, GNU ps sets the width to 132,
668 * if w is given more than once, it is "unlimited"
671 terminal_width
= (w_count
== 1) ? 132 : MAX_WIDTH
;
673 get_terminal_width_height(0, &terminal_width
, NULL
);
675 if (--terminal_width
> MAX_WIDTH
)
676 terminal_width
= MAX_WIDTH
;
679 /* -w is not supported, only -Z and/or -T */
680 opt_complementary
= "-";
681 opts
= getopt32(argv
, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T")IF_FEATURE_PS_LONG("l"));
685 if ((opts
& OPT_Z
) && is_selinux_enabled()) {
686 psscan_flags
= PSSCAN_PID
| PSSCAN_CONTEXT
687 | PSSCAN_STATE
| PSSCAN_COMM
;
688 puts(" PID CONTEXT STAT COMMAND");
692 psscan_flags
= PSSCAN_STATE
| PSSCAN_UIDGID
| PSSCAN_PID
| PSSCAN_PPID
693 | PSSCAN_TTY
| PSSCAN_STIME
| PSSCAN_UTIME
| PSSCAN_COMM
694 | PSSCAN_VSZ
| PSSCAN_RSS
;
695 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
701 * -PRI The priority of the process; higher numbers mean lower priority
703 * -ADDR The address of the process (?)
704 * SZ The size in blocks of the core image
705 * -WCHAN The event for which the process is waiting or sleeping
707 * TIME The cumulative execution time
709 * We don't show fields marked with '-'.
710 * We show VSZ and RSS instead of SZ.
711 * We also show STIME (standard says that -f shows it, -l doesn't).
713 puts("S UID PID PPID VSZ RSS TTY STIME TIME CMD");
714 # if ENABLE_FEATURE_PS_LONG
716 uptime
= get_uptime();
720 puts(" PID USER VSZ STAT COMMAND");
723 psscan_flags
|= PSSCAN_TASKS
;
728 while ((p
= procps_scan(p
, psscan_flags
)) != NULL
) {
731 if (psscan_flags
& PSSCAN_CONTEXT
) {
732 len
= printf("%5u %-32.32s %s ",
734 p
->context
? p
->context
: "unknown",
740 smart_ulltoa5(p
->vsz
, buf6
, " mgtpezy");
742 #if ENABLE_FEATURE_PS_LONG
744 char bufr
[6], stime_str
[6];
745 char tty
[2 * sizeof(int)*3 + 2];
747 unsigned sut
= (p
->stime
+ p
->utime
) / 100;
748 unsigned elapsed
= uptime
- (p
->start_time
/ 100);
749 time_t start
= now
- elapsed
;
750 struct tm
*tm
= localtime(&start
);
752 smart_ulltoa5(p
->rss
, bufr
, " mgtpezy");
755 if (p
->tty_major
== 136)
756 /* It should be pts/N, not ptsN, but N > 9
757 * will overflow field width...
759 endp
= stpcpy(tty
, "pts");
761 if (p
->tty_major
== 4) {
762 endp
= stpcpy(tty
, "tty");
763 if (p
->tty_minor
>= 64) {
769 endp
= tty
+ sprintf(tty
, "%d:", p
->tty_major
);
770 strcpy(endp
, utoa(p
->tty_minor
));
772 strftime(stime_str
, 6, (elapsed
>= (24 * 60 * 60)) ? "%b%d" : "%H:%M", tm
);
774 // S UID PID PPID VSZ RSS TTY STIME TIME CMD
775 len
= printf("%c %5u %5u %5u %5s %5s %-5s %s %02u:%02u:%02u ",
776 p
->state
[0], p
->uid
, p
->pid
, p
->ppid
, buf6
, bufr
, tty
,
777 stime_str
, sut
/ 3600, (sut
% 3600) / 60, sut
% 60);
781 const char *user
= get_cached_username(p
->uid
);
782 len
= printf("%5u %-8.8s %s %s ",
783 p
->pid
, user
, buf6
, p
->state
);
788 int sz
= terminal_width
- len
;
790 read_cmdline(buf
, sz
, p
->pid
, p
->comm
);
794 if (ENABLE_FEATURE_CLEAN_UP
)
795 clear_username_cache();
799 #endif /* !ENABLE_DESKTOP */