2 * Top users/processes display for Unix
4 * This program may be freely redistributed,
5 * but this entire comment MUST remain intact.
7 * Copyright (c) 1984, 1989, William LeFebvre, Rice University
8 * Copyright (c) 1989 - 1994, William LeFebvre, Northwestern University
9 * Copyright (c) 1994, 1995, William LeFebvre, Argonne National Laboratory
10 * Copyright (c) 1996, William LeFebvre, Group sys Consulting
15 #include <sys/types.h>
17 #include <sys/cdefs.h>
18 #include <sys/limits.h>
19 #include <sys/resource.h>
20 #include <sys/select.h>
21 #include <sys/signal.h>
36 #include "display.h" /* interface to display package */
37 #include "screen.h" /* interface to screen package */
43 /* Size of the stdio buffer given to stdout */
44 #define Buffersize 2048
47 "Copyright (c) 1984 through 1996, William LeFebvre";
49 typedef void sigret_t;
51 /* The buffer that stdio will use */
52 static char stdoutbuf[Buffersize];
54 static int fmt_flags = 0;
55 int show_args = false;
56 int pcpu_stats = false;
58 /* signal handling routines */
59 static sigret_t leave(int);
60 static sigret_t tstop(int);
61 static sigret_t top_winch(int);
63 static volatile sig_atomic_t leaveflag;
64 static volatile sig_atomic_t tstopflag;
65 static volatile sig_atomic_t winchflag;
67 /* values which need to be accessed by signal handlers */
68 static int max_topn; /* maximum displayable processes */
70 /* miscellaneous things */
71 struct process_select ps;
74 /* pointers to display routines */
75 static void (*d_loadave)(int mpid, double *avenrun) = i_loadave;
76 static void (*d_procstates)(int total, int *brkdn) = i_procstates;
77 static void (*d_cpustates)(int *states) = i_cpustates;
78 static void (*d_memory)(int *stats) = i_memory;
79 static void (*d_arc)(int *stats) = i_arc;
80 static void (*d_carc)(int *stats) = i_carc;
81 static void (*d_swap)(int *stats) = i_swap;
82 static void (*d_message)(void) = i_message;
83 static void (*d_header)(const char *text) = i_header;
84 static void (*d_process)(int line, char *thisline) = i_process;
86 static void reset_display(void);
88 static const struct option longopts[] = {
89 { "cpu-display-mode", no_argument, NULL, 'C' }, /* differs from orignal */
91 { "thread", no_argument, NULL, 'H' },
92 { "idle-procs", no_argument, NULL, 'I' },
93 { "jail", required_argument, NULL, 'J' },
94 { "per-cpu", no_argument, NULL, 'P' },
95 { "system-procs", no_argument, NULL, 'S' },
96 { "thread-id", no_argument, NULL, 'T' }, /* differs from orignal */
97 { "user", required_argument, NULL, 'U' },
98 { "all", no_argument, NULL, 'a' },
99 { "batch", no_argument, NULL, 'b' },
101 { "displays", required_argument, NULL, 'd' },
102 { "interactive", no_argument, NULL, 'i' },
103 { "jail-id", no_argument, NULL, 'j' },
104 { "display-mode", required_argument, NULL, 'm' },
105 /* n is identical to batch */
106 { "sort-order", required_argument, NULL, 'o' },
107 { "pid", required_argument, NULL, 'p' },
108 { "quick", no_argument, NULL, 'q' },
109 { "delay", required_argument, NULL, 's' },
110 { "threads", no_argument, NULL, 't' },
111 { "uids", no_argument, NULL, 'u' },
112 { "version", no_argument, NULL, 'v' },
113 { "swap", no_argument, NULL, 'w' },
114 { "system-idle-procs", no_argument, NULL, 'z' },
121 for (size_t i = 0; i < TOP_MAX_UIDS; ++i)
130 /* Add the uid if there's room */
131 for (; i < TOP_MAX_UIDS; ++i)
133 if (ps.uid[i] == -1 || ps.uid[i] == uid)
140 return (i == TOP_MAX_UIDS);
147 size_t where = TOP_MAX_UIDS;
149 /* Look for the user to remove - no problem if it's not there */
150 for (; i < TOP_MAX_UIDS; ++i)
154 if (ps.uid[i] == uid)
158 /* Make sure we don't leave a hole in the middle */
159 if (where != TOP_MAX_UIDS)
161 ps.uid[where] = ps.uid[i-1];
167 handle_user(char *buf, size_t buflen)
173 new_message(MT_standout, "Username to show (+ for all): ");
174 if (readline(buf, buflen, false) <= 0)
180 if (buf[0] == '+' || buf[0] == '-')
191 if ((uid = userid(buf2)) == -1)
193 new_message(MT_standout, " %s: unknown user", buf2);
209 new_message(MT_standout, " too many users, reset with '+'");
223 main(int argc, const char *argv[])
228 struct system_info system_info;
229 struct statics statics;
232 static char tempbuf1[50];
233 static char tempbuf2[50];
234 sigset_t old_sigmask, new_sigmask;
236 struct timeval delay = { 2, 0 };
237 int displays = 0; /* indicates unspecified */
240 char *(*get_userid)(int) = username;
241 const char *uname_field = "USERNAME";
242 const char *header_text;
244 const char **preset_argv;
246 const char **av = NULL;
248 bool do_unames = true;
249 char interactive = 2;
251 char topn_specified = false;
254 struct timeval timeout;
255 char *order_name = NULL;
260 /* set the buffer for stdout */
263 debug = fopen("debug.run", "w");
264 setbuffer(stdout, NULL, 0);
266 setbuffer(stdout, stdoutbuf, Buffersize);
272 /* initialize some selection options */
285 ps.thread_id = false;
287 /* get preset options from the environment */
288 if ((env_top = getenv("TOP")) != NULL)
290 av = preset_argv = argparse(env_top, &preset_argc);
293 /* set the dummy argument to an explanatory message, in case
294 getopt encounters a bad argument */
295 preset_argv[0] = "while processing environment";
298 /* process options */
300 /* if we're done doing the presets, then process the real arguments */
301 if (preset_argc == 0)
306 /* this should keep getopt happy... */
310 while ((i = getopt_long(ac, __DECONST(char * const *, av), "CSIHPabijJ:nquvzs:d:U:m:o:p:Ttw", longopts, NULL)) != EOF)
314 case 'v': /* show version number */
315 errx(0, "version FreeBSD");
318 case 'u': /* toggle uid/username display */
319 do_unames = !do_unames;
322 case 'U': /* display only username's processes */
323 if ((ps.uid[0] = userid(optarg)) == -1)
325 errx(1, "%s: unknown user\n", optarg);
329 case 'S': /* show system processes */
333 case 'I': /* show idle processes */
337 case 'i': /* go interactive regardless */
341 case 'n': /* batch, or non-interactive */
347 fmt_flags ^= FMT_SHOWARGS;
350 case 'd': /* number of displays to show */
351 if ((i = atoiwi(optarg)) == Invalid || i == 0)
353 warnx("warning: display count should be positive -- option ignored");
362 unsigned long long num;
365 num = strtonum(optarg, 0, INT_MAX, &errstr);
366 if (errstr != NULL || !find_pid(num)) {
367 fprintf(stderr, "%s: unknown pid\n", optarg);
377 double delay_d = strtod(optarg, &nptr);
380 warnx("warning: invalid delay");
383 else if (delay_d <= 0)
385 warnx("warning: seconds delay should be positive -- using default");
390 delay.tv_sec = delay_d;
391 delay.tv_usec = (delay_d - delay.tv_sec) * 1e6;
396 case 'q': /* be quick about it */
398 i = setpriority(PRIO_PROCESS, 0, PRIO_MIN);
399 if (i == -1 && errno != 0) {
400 warnx("warning: `-q' option failed (%m)");
405 case 'm': /* select display mode */
406 if (strcmp(optarg, "io") == 0) {
407 displaymode = DISP_IO;
408 } else if (strcmp(optarg, "cpu") == 0) {
409 displaymode = DISP_CPU;
411 errx(1, "warning: `-m' option can only take args 'io' or 'cpu'");
415 case 'o': /* select sort order */
428 ps.thread = !ps.thread;
432 ps.thread_id = !ps.thread_id;
439 case 'J': /* display only jail's processes */
440 if ((ps.jid = jail_getid(optarg)) == -1)
442 fprintf(stderr, "%s: unknown jail\n", optarg);
449 pcpu_stats = !pcpu_stats;
457 ps.kidle = !ps.kidle;
462 "[-abCHIijnPqStuvwz] [-d count] [-m io | cpu] [-o field] [-p pid]\n"
463 " [-s time] [-J jail] [-U username] [number]");
467 /* get count of top processes to display (if any) */
470 if ((topn = atoiwi(av[optind])) == Invalid)
472 warnx("warning: process display count should be non-negative -- using default");
477 topn_specified = true;
481 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
485 /* repeat only if we really did the preset arguments */
488 /* set constants for username/uid display correctly */
491 uname_field = " UID ";
495 /* initialize the kernel memory interface */
496 if (machine_init(&statics) == -1)
501 /* determine sorting order index, if necessary */
502 if (order_name != NULL)
504 if ((order_index = string_index(order_name, statics.order_names)) == -1)
506 const char * const *pp;
508 warnx("'%s' is not a recognized sorting order.", order_name);
509 fprintf(stderr, "\tTry one of these:");
510 pp = statics.order_names;
513 fprintf(stderr, " %s", *pp++);
520 /* initialize termcap */
521 init_termcap(interactive);
523 /* get the string to use for the process area header */
524 header_text = format_header(uname_field);
526 /* initialize display interface */
527 if ((max_topn = display_init(&statics)) == -1)
529 errx(4, "can't allocate sufficient memory");
532 /* print warning if user requested more processes than we can display */
535 warnx("warning: this terminal can only display %d processes.", max_topn);
539 /* adjust for topn == Infinity */
540 if (topn == Infinity)
543 * For smart terminals, infinity really means everything that can
544 * be displayed, or Largest.
545 * On dumb terminals, infinity means every process in the system!
546 * We only really want to do that if it was explicitly specified.
547 * This is always the case when "Default_TOPN != Infinity". But if
548 * topn wasn't explicitly specified and we are on a dumb terminal
549 * and the default is Infinity, then (and only then) we use
550 * "Nominal_TOPN" instead.
552 topn = smart_terminal ? Largest :
553 (topn_specified ? Largest : Nominal_TOPN);
556 /* set header display accordingly */
557 display_header(topn > 0);
559 /* determine interactive state */
560 if (interactive == 2)
562 interactive = smart_terminal;
565 /* if # of displays not specified, fill it in */
568 displays = smart_terminal ? Infinity : 1;
571 /* hold interrupt signals while setting up the screen and the handlers */
573 sigemptyset(&new_sigmask);
574 sigaddset(&new_sigmask, SIGINT);
575 sigaddset(&new_sigmask, SIGQUIT);
576 sigaddset(&new_sigmask, SIGTSTP);
577 sigprocmask(SIG_BLOCK, &new_sigmask, &old_sigmask);
579 signal(SIGINT, leave);
580 signal(SIGQUIT, leave);
581 signal(SIGTSTP, tstop);
582 signal(SIGWINCH, top_winch);
583 sigprocmask(SIG_SETMASK, &old_sigmask, NULL);
586 fputs("....", stderr);
595 * main loop -- repeat while display count is positive or while it
596 * indicates infinity (by being -1)
599 while ((displays == -1) || (displays-- > 0))
601 int (*compare)(const void * const, const void * const);
604 /* get the current stats */
605 get_system_info(&system_info);
607 compare = compares[order_index];
609 /* get the current set of processes */
611 get_process_info(&system_info, &ps, compare);
613 /* display the load averages */
614 (*d_loadave)(system_info.last_pid,
615 system_info.load_avg);
617 /* display the current time */
618 /* this method of getting the time SHOULD be fairly portable */
620 i_uptime(&system_info.boottime, &curr_time);
621 i_timeofday(&curr_time);
623 /* display process state breakdown */
624 (*d_procstates)(system_info.p_total,
625 system_info.procstates);
626 (*d_cpustates)(system_info.cpustates);
628 /* display memory stats */
629 (*d_memory)(system_info.memory);
630 (*d_arc)(system_info.arc);
631 (*d_carc)(system_info.carc);
633 /* display swap stats */
634 (*d_swap)(system_info.swap);
636 /* handle message area */
639 /* update the header area */
640 (*d_header)(header_text);
644 /* determine number of processes to actually display */
645 /* this number will be the smallest of: active processes,
646 number user requested, number current screen accomodates */
647 active_procs = system_info.p_pactive;
648 if (active_procs > topn)
652 if (active_procs > max_topn)
654 active_procs = max_topn;
657 /* now show the top "n" processes. */
658 for (i = 0; i < active_procs; i++)
660 (*d_process)(i, format_next_process(processes, get_userid,
669 /* do end-screen processing */
672 /* now, flush the output buffer */
673 if (fflush(stdout) != 0)
675 new_message(MT_standout, " Write error on stdout");
680 /* only do the rest if we have more displays to show */
683 /* switch out for new display on smart terminals */
692 d_loadave = u_loadave;
693 d_procstates = u_procstates;
694 d_cpustates = u_cpustates;
699 d_message = u_message;
701 d_process = u_process;
709 select(0, NULL, NULL, NULL, &timeout);
715 else while (no_command)
717 /* assume valid command unless told otherwise */
720 /* set up arguments for select with timeout */
722 FD_SET(0, &readfds); /* for standard input */
731 /* move to the lower left */
735 /* default the signal handler action */
736 signal(SIGTSTP, SIG_DFL);
738 /* unblock the signal and send ourselves one */
739 sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
742 /* reset the signal handler */
743 signal(SIGTSTP, tstop);
753 /* reascertain the screen dimensions */
756 /* tell display to resize */
757 max_topn = display_resize();
759 /* reset the signal handler */
760 signal(SIGWINCH, top_winch);
767 /* wait for either input or the end of the delay period */
768 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
769 if (sel_ret < 0 && errno != EINTR)
775 const struct command *cptr;
777 /* something to read -- clear the message area first */
780 /* now read it and convert to command strchr */
781 /* (use "change" as a temporary to hold strchr) */
782 if (read(0, &ch, 1) != 1)
784 /* read error: either 0 or -1 */
785 new_message(MT_standout, " Read error on stdin");
789 if (ch == '\r' || ch == '\n') {
793 while (cptr->c != '\0') {
799 if (cptr->c == '\0') {
800 new_message(MT_standout, " Command not understood");
804 if (overstrike && !cptr->available_to_dumb)
806 new_message(MT_standout,
807 " Command cannot be handled by this terminal");
814 case CMD_redraw: /* redraw screen */
818 case CMD_update: /* merely update display */
829 top_standout("Hit any key to continue: ");
834 case CMD_errors: /* show errors */
835 if (error_count() == 0)
837 new_message(MT_standout,
838 " Currently no errors to report.");
847 top_standout("Hit any key to continue: ");
854 new_message(MT_standout,
855 "Number of processes to show: ");
856 newval = readline(tempbuf1, 8, true);
859 if (newval > max_topn)
861 new_message(MT_standout | MT_delayed,
862 " This terminal can only display %d processes.",
869 /* inhibit the header */
870 display_header(false);
872 else if (newval > topn && topn == 0)
874 /* redraw the header */
875 display_header(true);
882 case CMD_delay: /* new seconds delay */
883 new_message(MT_standout, "Seconds to delay: ");
884 if ((i = readline(tempbuf1, 8, false)) > 0)
886 double delay_d = strtod(tempbuf1, &nptr);
887 if (nptr == tempbuf1 || delay_d <= 0)
889 new_message(MT_standout, " Invalid delay");
895 delay.tv_sec = delay_d;
896 delay.tv_usec = (delay_d - delay.tv_sec) * 1e6;
902 case CMD_grep: /* grep command name */
903 new_message(MT_standout,
904 "Grep command name (+ for all): ");
905 if (readline(tempbuf1, sizeof(tempbuf1), false) > 0) {
907 if (tempbuf1[0] == '+' && tempbuf1[1] == '\0') {
909 } else if ((ps.command = strdup(tempbuf1)) == NULL)
915 case CMD_displays: /* change display count */
916 new_message(MT_standout,
917 "Displays to show (currently %s): ",
918 displays == -1 ? "infinite" :
920 if ((i = readline(tempbuf1, 10, true)) > 0)
931 case CMD_kill: /* kill program */
932 new_message(0, "kill ");
933 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
935 if ((errmsg = kill_procs(tempbuf2)) != NULL)
937 new_message(MT_standout, "%s", errmsg);
948 case CMD_renice: /* renice program */
949 new_message(0, "renice ");
950 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
952 if ((errmsg = renice_procs(tempbuf2)) != NULL)
954 new_message(MT_standout, "%s", errmsg);
967 new_message(MT_standout | MT_delayed,
968 " %sisplaying idle processes.",
969 ps.idle ? "D" : "Not d");
975 new_message(MT_standout | MT_delayed,
976 " %sisplaying self.",
977 (ps.self) ? "D" : "Not d");
982 if (handle_user(tempbuf2, sizeof(tempbuf2)))
987 ps.thread = !ps.thread;
988 new_message(MT_standout | MT_delayed,
989 " Displaying threads %s",
990 ps.thread ? "separately" : "as a count");
991 header_text = format_header(uname_field);
997 ps.thread_id = !ps.thread_id;
998 new_message(MT_standout | MT_delayed,
1000 ps.thread_id ? "tid" : "pid");
1001 header_text = format_header(uname_field);
1008 new_message(MT_standout | MT_delayed,
1009 " Displaying %s CPU",
1010 ps.wcpu ? "weighted" : "raw");
1011 header_text = format_header(uname_field);
1016 displaymode = displaymode == DISP_IO ? DISP_CPU : DISP_IO;
1017 new_message(MT_standout | MT_delayed,
1018 " Displaying %s statistics.",
1019 displaymode == DISP_IO ? "IO" : "CPU");
1020 header_text = format_header(uname_field);
1021 display_header(true);
1022 d_header = i_header;
1026 ps.system = !ps.system;
1027 new_message(MT_standout | MT_delayed,
1028 " %sisplaying system processes.",
1029 ps.system ? "D" : "Not d");
1032 fmt_flags ^= FMT_SHOWARGS;
1033 show_args = fmt_flags & FMT_SHOWARGS;
1034 new_message(MT_standout | MT_delayed,
1035 " %sisplaying process arguments.",
1036 fmt_flags & FMT_SHOWARGS ? "D" : "Not d");
1039 new_message(MT_standout,
1041 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
1043 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1045 new_message(MT_standout,
1046 " %s: unrecognized sorting order", tempbuf2);
1062 new_message(MT_standout | MT_delayed,
1063 " %sisplaying jail ID.",
1064 ps.jail ? "D" : "Not d");
1065 header_text = format_header(uname_field);
1071 new_message(MT_standout,
1072 "Jail to show (+ for all): ");
1073 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
1075 if (tempbuf2[0] == '+' &&
1076 tempbuf2[1] == '\0')
1080 else if ((i = jail_getid(tempbuf2)) == -1)
1082 new_message(MT_standout,
1083 " %s: unknown jail", tempbuf2);
1092 new_message(MT_standout |
1093 MT_delayed, " Displaying jail "
1096 format_header(uname_field);
1108 ps.kidle = !ps.kidle;
1109 new_message(MT_standout | MT_delayed,
1110 " %sisplaying system idle process.",
1111 ps.kidle ? "D" : "Not d");
1115 pcpu_stats = !pcpu_stats;
1116 new_message(MT_standout | MT_delayed,
1117 " Displaying %sCPU statistics.",
1118 pcpu_stats ? "per-" : "global ");
1120 max_topn = display_updatecpus(&statics);
1126 new_message(MT_standout | MT_delayed,
1127 " %sisplaying per-process swap usage.",
1128 ps.swap ? "D" : "Not d");
1129 header_text = format_header(uname_field);
1134 new_message(MT_standout,
1135 "Process id to show (+ for all): ");
1136 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0) {
1137 if (tempbuf2[0] == '+' &&
1138 tempbuf2[1] == '\0') {
1141 unsigned long long num;
1144 num = strtonum(tempbuf2, 0, INT_MAX,
1146 if (errstr != NULL || !find_pid(num)) {
1147 new_message(MT_standout,
1152 ps.pid = (pid_t)num;
1160 assert(false && "reached switch without command");
1165 /* flush out stuff that may have been written */
1178 * reset_display() - reset all the display routine pointers so that entire
1179 * screen will get redrawn.
1185 d_loadave = i_loadave;
1186 d_procstates = i_procstates;
1187 d_cpustates = i_cpustates;
1188 d_memory = i_memory;
1192 d_message = i_message;
1193 d_header = i_header;
1194 d_process = i_process;
1202 leave(int i __unused) /* exit under normal conditions -- INT handler */
1209 tstop(int i __unused) /* SIGTSTP handler */
1216 top_winch(int i __unused) /* SIGWINCH handler */
1223 quit(int status) /* exit under duress */