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 pcpu_stats = false;
57 /* signal handling routines */
58 static sigret_t leave(int);
59 static sigret_t tstop(int);
60 static sigret_t top_winch(int);
62 static volatile sig_atomic_t leaveflag;
63 static volatile sig_atomic_t tstopflag;
64 static volatile sig_atomic_t winchflag;
66 /* values which need to be accessed by signal handlers */
67 static int max_topn; /* maximum displayable processes */
69 /* miscellaneous things */
70 struct process_select ps;
73 /* pointers to display routines */
74 static void (*d_loadave)(int mpid, double *avenrun) = i_loadave;
75 static void (*d_procstates)(int total, int *brkdn) = i_procstates;
76 static void (*d_cpustates)(int *states) = i_cpustates;
77 static void (*d_memory)(int *stats) = i_memory;
78 static void (*d_arc)(int *stats) = i_arc;
79 static void (*d_carc)(int *stats) = i_carc;
80 static void (*d_swap)(int *stats) = i_swap;
81 static void (*d_message)(void) = i_message;
82 static void (*d_header)(const char *text) = i_header;
83 static void (*d_process)(int line, char *thisline) = i_process;
85 static void reset_display(void);
87 static const struct option longopts[] = {
88 { "cpu-display-mode", no_argument, NULL, 'C' }, /* differs from orignal */
90 { "thread", no_argument, NULL, 'H' },
91 { "idle-procs", no_argument, NULL, 'I' },
92 { "jail", required_argument, NULL, 'J' },
93 { "per-cpu", no_argument, NULL, 'P' },
94 { "system-procs", no_argument, NULL, 'S' },
95 { "thread-id", no_argument, NULL, 'T' }, /* differs from orignal */
96 { "user", required_argument, NULL, 'U' },
97 { "all", no_argument, NULL, 'a' },
98 { "batch", no_argument, NULL, 'b' },
100 { "displays", required_argument, NULL, 'd' },
101 { "interactive", no_argument, NULL, 'i' },
102 { "jail-id", no_argument, NULL, 'j' },
103 { "display-mode", required_argument, NULL, 'm' },
104 /* n is identical to batch */
105 { "sort-order", required_argument, NULL, 'o' },
106 { "pid", required_argument, NULL, 'p' },
107 { "quick", no_argument, NULL, 'q' },
108 { "delay", required_argument, NULL, 's' },
109 { "threads", no_argument, NULL, 't' },
110 { "uids", no_argument, NULL, 'u' },
111 { "version", no_argument, NULL, 'v' },
112 { "swap", no_argument, NULL, 'w' },
113 { "system-idle-procs", no_argument, NULL, 'z' },
120 for (size_t i = 0; i < TOP_MAX_UIDS; ++i)
129 /* Add the uid if there's room */
130 for (; i < TOP_MAX_UIDS; ++i)
132 if (ps.uid[i] == -1 || ps.uid[i] == uid)
139 return (i == TOP_MAX_UIDS);
146 size_t where = TOP_MAX_UIDS;
148 /* Look for the user to remove - no problem if it's not there */
149 for (; i < TOP_MAX_UIDS; ++i)
153 if (ps.uid[i] == uid)
157 /* Make sure we don't leave a hole in the middle */
158 if (where != TOP_MAX_UIDS)
160 ps.uid[where] = ps.uid[i-1];
166 handle_user(char *buf, size_t buflen)
172 new_message(MT_standout, "Username to show (+ for all): ");
173 if (readline(buf, buflen, false) <= 0)
179 if (buf[0] == '+' || buf[0] == '-')
190 if ((uid = userid(buf2)) == -1)
192 new_message(MT_standout, " %s: unknown user", buf2);
208 new_message(MT_standout, " too many users, reset with '+'");
222 main(int argc, char *argv[])
227 struct system_info system_info;
228 struct statics statics;
231 static char tempbuf1[50];
232 static char tempbuf2[50];
233 sigset_t old_sigmask, new_sigmask;
236 int displays = 0; /* indicates unspecified */
239 char *(*get_userid)(int) = username;
240 const char *uname_field = "USERNAME";
241 const char *header_text;
243 const char **preset_argv;
245 const char **av = NULL;
247 bool do_unames = true;
248 char interactive = 2;
250 char topn_specified = false;
253 struct timeval timeout;
254 char *order_name = NULL;
259 /* set the buffer for stdout */
262 debug = fopen("debug.run", "w");
263 setbuffer(stdout, NULL, 0);
265 setbuffer(stdout, stdoutbuf, Buffersize);
271 /* initialize some selection options */
284 ps.thread_id = false;
286 /* get preset options from the environment */
287 if ((env_top = getenv("TOP")) != NULL)
289 av = preset_argv = argparse(env_top, &preset_argc);
292 /* set the dummy argument to an explanatory message, in case
293 getopt encounters a bad argument */
294 preset_argv[0] = "while processing environment";
297 /* process options */
299 /* if we're done doing the presets, then process the real arguments */
300 if (preset_argc == 0)
305 /* this should keep getopt happy... */
309 while ((i = getopt_long(ac, av, "CSIHPabijJ:nquvzs:d:U:m:o:p:Ttw", longopts, NULL)) != EOF)
313 case 'v': /* show version number */
314 errx(0, "version FreeBSD");
317 case 'u': /* toggle uid/username display */
318 do_unames = !do_unames;
321 case 'U': /* display only username's processes */
322 if ((ps.uid[0] = userid(optarg)) == -1)
324 errx(1, "%s: unknown user\n", optarg);
328 case 'S': /* show system processes */
332 case 'I': /* show idle processes */
336 case 'i': /* go interactive regardless */
340 case 'n': /* batch, or non-interactive */
346 fmt_flags ^= FMT_SHOWARGS;
349 case 'd': /* number of displays to show */
350 if ((i = atoiwi(optarg)) == Invalid || i == 0)
352 warnx("warning: display count should be positive -- option ignored");
361 unsigned long long num;
364 num = strtonum(optarg, 0, INT_MAX, &errstr);
365 if (errstr != NULL || !find_pid(num)) {
366 fprintf(stderr, "%s: unknown pid\n", optarg);
375 delay = strtod(optarg, &nptr);
376 if (nptr == optarg) {
377 warnx("warning: invalid delay");
382 warnx("warning: seconds delay should be positive -- using default");
389 case 'q': /* be quick about it */
391 i = setpriority(PRIO_PROCESS, 0, PRIO_MIN);
392 if (i == -1 && errno != 0) {
393 warnx("warning: `-q' option failed (%m)");
398 case 'm': /* select display mode */
399 if (strcmp(optarg, "io") == 0) {
400 displaymode = DISP_IO;
401 } else if (strcmp(optarg, "cpu") == 0) {
402 displaymode = DISP_CPU;
404 errx(1, "warning: `-m' option can only take args 'io' or 'cpu'");
408 case 'o': /* select sort order */
421 ps.thread = !ps.thread;
425 ps.thread_id = !ps.thread_id;
432 case 'J': /* display only jail's processes */
433 if ((ps.jid = jail_getid(optarg)) == -1)
435 fprintf(stderr, "%s: unknown jail\n", optarg);
442 pcpu_stats = !pcpu_stats;
450 ps.kidle = !ps.kidle;
455 "[-abCHIijnPqStuvwz] [-d count] [-m io | cpu] [-o field] [-p pid]\n"
456 " [-s time] [-J jail] [-U username] [number]");
460 /* get count of top processes to display (if any) */
463 if ((topn = atoiwi(av[optind])) == Invalid)
465 warnx("warning: process display count should be non-negative -- using default");
470 topn_specified = true;
474 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
478 /* repeat only if we really did the preset arguments */
481 /* set constants for username/uid display correctly */
484 uname_field = " UID ";
488 /* initialize the kernel memory interface */
489 if (machine_init(&statics) == -1)
494 /* determine sorting order index, if necessary */
495 if (order_name != NULL)
497 if ((order_index = string_index(order_name, statics.order_names)) == -1)
499 const char * const *pp;
501 warnx("'%s' is not a recognized sorting order.", order_name);
502 fprintf(stderr, "\tTry one of these:");
503 pp = statics.order_names;
506 fprintf(stderr, " %s", *pp++);
513 /* initialize termcap */
514 init_termcap(interactive);
516 /* get the string to use for the process area header */
517 header_text = format_header(uname_field);
519 /* initialize display interface */
520 if ((max_topn = display_init(&statics)) == -1)
522 errx(4, "can't allocate sufficient memory");
525 /* print warning if user requested more processes than we can display */
528 warnx("warning: this terminal can only display %d processes.", max_topn);
532 /* adjust for topn == Infinity */
533 if (topn == Infinity)
536 * For smart terminals, infinity really means everything that can
537 * be displayed, or Largest.
538 * On dumb terminals, infinity means every process in the system!
539 * We only really want to do that if it was explicitly specified.
540 * This is always the case when "Default_TOPN != Infinity". But if
541 * topn wasn't explicitly specified and we are on a dumb terminal
542 * and the default is Infinity, then (and only then) we use
543 * "Nominal_TOPN" instead.
545 topn = smart_terminal ? Largest :
546 (topn_specified ? Largest : Nominal_TOPN);
549 /* set header display accordingly */
550 display_header(topn > 0);
552 /* determine interactive state */
553 if (interactive == 2)
555 interactive = smart_terminal;
558 /* if # of displays not specified, fill it in */
561 displays = smart_terminal ? Infinity : 1;
564 /* hold interrupt signals while setting up the screen and the handlers */
566 sigemptyset(&new_sigmask);
567 sigaddset(&new_sigmask, SIGINT);
568 sigaddset(&new_sigmask, SIGQUIT);
569 sigaddset(&new_sigmask, SIGTSTP);
570 sigprocmask(SIG_BLOCK, &new_sigmask, &old_sigmask);
572 signal(SIGINT, leave);
573 signal(SIGQUIT, leave);
574 signal(SIGTSTP, tstop);
575 signal(SIGWINCH, top_winch);
576 sigprocmask(SIG_SETMASK, &old_sigmask, NULL);
579 fputs("....", stderr);
588 * main loop -- repeat while display count is positive or while it
589 * indicates infinity (by being -1)
592 while ((displays == -1) || (displays-- > 0))
594 int (*compare)(const void * const, const void * const);
597 /* get the current stats */
598 get_system_info(&system_info);
600 compare = compares[order_index];
602 /* get the current set of processes */
604 get_process_info(&system_info, &ps, compare);
606 /* display the load averages */
607 (*d_loadave)(system_info.last_pid,
608 system_info.load_avg);
610 /* display the current time */
611 /* this method of getting the time SHOULD be fairly portable */
613 i_uptime(&system_info.boottime, &curr_time);
614 i_timeofday(&curr_time);
616 /* display process state breakdown */
617 (*d_procstates)(system_info.p_total,
618 system_info.procstates);
619 (*d_cpustates)(system_info.cpustates);
621 /* display memory stats */
622 (*d_memory)(system_info.memory);
623 (*d_arc)(system_info.arc);
624 (*d_carc)(system_info.carc);
626 /* display swap stats */
627 (*d_swap)(system_info.swap);
629 /* handle message area */
632 /* update the header area */
633 (*d_header)(header_text);
637 /* determine number of processes to actually display */
638 /* this number will be the smallest of: active processes,
639 number user requested, number current screen accomodates */
640 active_procs = system_info.p_pactive;
641 if (active_procs > topn)
645 if (active_procs > max_topn)
647 active_procs = max_topn;
650 /* now show the top "n" processes. */
651 for (i = 0; i < active_procs; i++)
653 (*d_process)(i, format_next_process(processes, get_userid,
662 /* do end-screen processing */
665 /* now, flush the output buffer */
666 if (fflush(stdout) != 0)
668 new_message(MT_standout, " Write error on stdout");
673 /* only do the rest if we have more displays to show */
676 /* switch out for new display on smart terminals */
685 d_loadave = u_loadave;
686 d_procstates = u_procstates;
687 d_cpustates = u_cpustates;
692 d_message = u_message;
694 d_process = u_process;
707 else while (no_command)
709 /* assume valid command unless told otherwise */
712 /* set up arguments for select with timeout */
714 FD_SET(0, &readfds); /* for standard input */
715 timeout.tv_sec = delay;
724 /* move to the lower left */
728 /* default the signal handler action */
729 signal(SIGTSTP, SIG_DFL);
731 /* unblock the signal and send ourselves one */
732 sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
735 /* reset the signal handler */
736 signal(SIGTSTP, tstop);
746 /* reascertain the screen dimensions */
749 /* tell display to resize */
750 max_topn = display_resize();
752 /* reset the signal handler */
753 signal(SIGWINCH, top_winch);
760 /* wait for either input or the end of the delay period */
761 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
762 if (sel_ret < 0 && errno != EINTR)
768 const struct command *cptr;
770 /* something to read -- clear the message area first */
773 /* now read it and convert to command strchr */
774 /* (use "change" as a temporary to hold strchr) */
775 if (read(0, &ch, 1) != 1)
777 /* read error: either 0 or -1 */
778 new_message(MT_standout, " Read error on stdin");
782 if (ch == '\r' || ch == '\n') {
786 while (cptr->c != '\0') {
792 if (cptr->c == '\0') {
793 new_message(MT_standout, " Command not understood");
797 if (overstrike && !cptr->available_to_dumb)
799 new_message(MT_standout,
800 " Command cannot be handled by this terminal");
807 case CMD_redraw: /* redraw screen */
811 case CMD_update: /* merely update display */
822 top_standout("Hit any key to continue: ");
827 case CMD_errors: /* show errors */
828 if (error_count() == 0)
830 new_message(MT_standout,
831 " Currently no errors to report.");
840 top_standout("Hit any key to continue: ");
847 new_message(MT_standout,
848 "Number of processes to show: ");
849 newval = readline(tempbuf1, 8, true);
852 if (newval > max_topn)
854 new_message(MT_standout | MT_delayed,
855 " This terminal can only display %d processes.",
862 /* inhibit the header */
863 display_header(false);
865 else if (newval > topn && topn == 0)
867 /* redraw the header */
868 display_header(true);
875 case CMD_delay: /* new seconds delay */
876 new_message(MT_standout, "Seconds to delay: ");
877 if ((i = readline(tempbuf1, 8, true)) > -1)
879 if ((delay = i) == 0)
887 case CMD_displays: /* change display count */
888 new_message(MT_standout,
889 "Displays to show (currently %s): ",
890 displays == -1 ? "infinite" :
892 if ((i = readline(tempbuf1, 10, true)) > 0)
903 case CMD_kill: /* kill program */
904 new_message(0, "kill ");
905 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
907 if ((errmsg = kill_procs(tempbuf2)) != NULL)
909 new_message(MT_standout, "%s", errmsg);
920 case CMD_renice: /* renice program */
921 new_message(0, "renice ");
922 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
924 if ((errmsg = renice_procs(tempbuf2)) != NULL)
926 new_message(MT_standout, "%s", errmsg);
939 new_message(MT_standout | MT_delayed,
940 " %sisplaying idle processes.",
941 ps.idle ? "D" : "Not d");
947 new_message(MT_standout | MT_delayed,
948 " %sisplaying self.",
949 (ps.self) ? "D" : "Not d");
954 if (handle_user(tempbuf2, sizeof(tempbuf2)))
959 ps.thread = !ps.thread;
960 new_message(MT_standout | MT_delayed,
961 " Displaying threads %s",
962 ps.thread ? "separately" : "as a count");
963 header_text = format_header(uname_field);
969 ps.thread_id = !ps.thread_id;
970 new_message(MT_standout | MT_delayed,
972 ps.thread_id ? "tid" : "pid");
973 header_text = format_header(uname_field);
980 new_message(MT_standout | MT_delayed,
981 " Displaying %s CPU",
982 ps.wcpu ? "weighted" : "raw");
983 header_text = format_header(uname_field);
988 displaymode = displaymode == DISP_IO ? DISP_CPU : DISP_IO;
989 new_message(MT_standout | MT_delayed,
990 " Displaying %s statistics.",
991 displaymode == DISP_IO ? "IO" : "CPU");
992 header_text = format_header(uname_field);
993 display_header(true);
998 ps.system = !ps.system;
999 new_message(MT_standout | MT_delayed,
1000 " %sisplaying system processes.",
1001 ps.system ? "D" : "Not d");
1004 fmt_flags ^= FMT_SHOWARGS;
1005 new_message(MT_standout | MT_delayed,
1006 " %sisplaying process arguments.",
1007 fmt_flags & FMT_SHOWARGS ? "D" : "Not d");
1010 new_message(MT_standout,
1012 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
1014 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1016 new_message(MT_standout,
1017 " %s: unrecognized sorting order", tempbuf2);
1033 new_message(MT_standout | MT_delayed,
1034 " %sisplaying jail ID.",
1035 ps.jail ? "D" : "Not d");
1036 header_text = format_header(uname_field);
1042 new_message(MT_standout,
1043 "Jail to show (+ for all): ");
1044 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
1046 if (tempbuf2[0] == '+' &&
1047 tempbuf2[1] == '\0')
1051 else if ((i = jail_getid(tempbuf2)) == -1)
1053 new_message(MT_standout,
1054 " %s: unknown jail", tempbuf2);
1063 new_message(MT_standout |
1064 MT_delayed, " Displaying jail "
1067 format_header(uname_field);
1079 ps.kidle = !ps.kidle;
1080 new_message(MT_standout | MT_delayed,
1081 " %sisplaying system idle process.",
1082 ps.kidle ? "D" : "Not d");
1086 pcpu_stats = !pcpu_stats;
1087 new_message(MT_standout | MT_delayed,
1088 " Displaying %sCPU statistics.",
1089 pcpu_stats ? "per-" : "global ");
1091 max_topn = display_updatecpus(&statics);
1097 new_message(MT_standout | MT_delayed,
1098 " %sisplaying per-process swap usage.",
1099 ps.swap ? "D" : "Not d");
1100 header_text = format_header(uname_field);
1105 new_message(MT_standout,
1106 "Process id to show (+ for all): ");
1107 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0) {
1108 if (tempbuf2[0] == '+' &&
1109 tempbuf2[1] == '\0') {
1112 unsigned long long num;
1115 num = strtonum(tempbuf2, 0, INT_MAX,
1117 if (errstr != NULL || !find_pid(num)) {
1118 new_message(MT_standout,
1123 ps.pid = (pid_t)num;
1131 assert(false && "reached switch without command");
1136 /* flush out stuff that may have been written */
1149 * reset_display() - reset all the display routine pointers so that entire
1150 * screen will get redrawn.
1156 d_loadave = i_loadave;
1157 d_procstates = i_procstates;
1158 d_cpustates = i_cpustates;
1159 d_memory = i_memory;
1163 d_message = i_message;
1164 d_header = i_header;
1165 d_process = i_process;
1173 leave(int i __unused) /* exit under normal conditions -- INT handler */
1180 tstop(int i __unused) /* SIGTSTP handler */
1187 top_winch(int i __unused) /* SIGWINCH handler */
1194 quit(int status) /* exit under duress */