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>
35 #include "display.h" /* interface to display package */
36 #include "screen.h" /* interface to screen package */
42 /* Size of the stdio buffer given to stdout */
43 #define Buffersize 2048
46 "Copyright (c) 1984 through 1996, William LeFebvre";
48 typedef void sigret_t;
50 /* The buffer that stdio will use */
51 static char stdoutbuf[Buffersize];
53 static int fmt_flags = 0;
54 int pcpu_stats = false;
56 /* signal handling routines */
57 static sigret_t leave(int);
58 static sigret_t tstop(int);
59 static sigret_t top_winch(int);
61 static volatile sig_atomic_t leaveflag;
62 static volatile sig_atomic_t tstopflag;
63 static volatile sig_atomic_t winchflag;
65 /* values which need to be accessed by signal handlers */
66 static int max_topn; /* maximum displayable processes */
68 /* miscellaneous things */
69 struct process_select ps;
70 const char * myname = "top";
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' }
119 for (size_t i = 0; i < TOP_MAX_UIDS; ++i)
128 /* Add the uid if there's room */
129 for (; i < TOP_MAX_UIDS; ++i)
131 if (ps.uid[i] == -1 || ps.uid[i] == uid)
138 return (i == TOP_MAX_UIDS);
145 size_t where = TOP_MAX_UIDS;
147 /* Look for the user to remove - no problem if it's not there */
148 for (; i < TOP_MAX_UIDS; ++i)
152 if (ps.uid[i] == uid)
156 /* Make sure we don't leave a hole in the middle */
157 if (where != TOP_MAX_UIDS)
159 ps.uid[where] = ps.uid[i-1];
165 handle_user(char *buf, size_t buflen)
171 new_message(MT_standout, "Username to show (+ for all): ");
172 if (readline(buf, buflen, false) <= 0)
178 if (buf[0] == '+' || buf[0] == '-')
189 if ((uid = userid(buf2)) == -1)
191 new_message(MT_standout, " %s: unknown user", buf2);
207 new_message(MT_standout, " too many users, reset with '+'");
221 main(int argc, char *argv[])
226 struct system_info system_info;
227 struct statics statics;
230 static char tempbuf1[50];
231 static char tempbuf2[50];
232 sigset_t old_sigmask, new_sigmask;
235 int displays = 0; /* indicates unspecified */
238 char *(*get_userid)(int) = username;
239 const char *uname_field = "USERNAME";
240 const char *header_text;
242 const char **preset_argv;
244 const char **av = NULL;
246 bool do_unames = true;
247 char interactive = 2;
249 char topn_specified = false;
252 struct timeval timeout;
253 char *order_name = NULL;
257 /* set the buffer for stdout */
260 debug = fopen("debug.run", "w");
261 setbuffer(stdout, NULL, 0);
263 setbuffer(stdout, stdoutbuf, Buffersize);
268 if ((myname = strrchr(argv[0], '/')) == 0)
281 /* initialize some selection options */
294 ps.thread_id = false;
296 /* get preset options from the environment */
297 if ((env_top = getenv("TOP")) != NULL)
299 av = preset_argv = argparse(env_top, &preset_argc);
302 /* set the dummy argument to an explanatory message, in case
303 getopt encounters a bad argument */
304 preset_argv[0] = "while processing environment";
307 /* process options */
309 /* if we're done doing the presets, then process the real arguments */
310 if (preset_argc == 0)
315 /* this should keep getopt happy... */
319 while ((i = getopt_long(ac, av, "CSIHPabijJ:nquvzs:d:U:m:o:p:Ttw", longopts, NULL)) != EOF)
323 case 'v': /* show version number */
324 fprintf(stderr, "%s: version FreeBSD\n", myname);
328 case 'u': /* toggle uid/username display */
329 do_unames = !do_unames;
332 case 'U': /* display only username's processes */
333 if ((ps.uid[0] = userid(optarg)) == -1)
335 fprintf(stderr, "%s: unknown user\n", optarg);
340 case 'S': /* show system processes */
344 case 'I': /* show idle processes */
348 case 'i': /* go interactive regardless */
352 case 'n': /* batch, or non-interactive */
358 fmt_flags ^= FMT_SHOWARGS;
361 case 'd': /* number of displays to show */
362 if ((i = atoiwi(optarg)) == Invalid || i == 0)
365 "%s: warning: display count should be positive -- option ignored\n",
375 unsigned long long num;
378 num = strtonum(optarg, 0, INT_MAX, &errstr);
379 if (errstr != NULL || !find_pid(num)) {
380 fprintf(stderr, "%s: unknown pid\n", optarg);
389 delay = strtod(optarg, NULL);
392 "%s: warning: seconds delay should be positive -- using default\n",
400 case 'q': /* be quick about it */
402 i = setpriority(PRIO_PROCESS, 0, PRIO_MIN);
403 if (i == -1 && errno != 0) {
405 "%s: warning: `-q' option failed (%m)\n", myname);
410 case 'm': /* select display mode */
411 if (strcmp(optarg, "io") == 0) {
412 displaymode = DISP_IO;
413 } else if (strcmp(optarg, "cpu") == 0) {
414 displaymode = DISP_CPU;
417 "%s: warning: `-m' option can only take args "
424 case 'o': /* select sort order */
437 ps.thread = !ps.thread;
441 ps.thread_id = !ps.thread_id;
448 case 'J': /* display only jail's processes */
449 if ((ps.jid = jail_getid(optarg)) == -1)
451 fprintf(stderr, "%s: unknown jail\n", optarg);
458 pcpu_stats = !pcpu_stats;
466 ps.kidle = !ps.kidle;
471 "Usage: %s [-abCHIijnPqStuvwz] [-d count] [-m io | cpu] [-o field] [-p pid]\n"
472 " [-s time] [-J jail] [-U username] [number]\n",
478 /* get count of top processes to display (if any) */
481 if ((topn = atoiwi(av[optind])) == Invalid)
484 "%s: warning: process display count should be non-negative -- using default\n",
490 topn_specified = true;
494 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
498 /* repeat only if we really did the preset arguments */
501 /* set constants for username/uid display correctly */
504 uname_field = " UID ";
508 /* initialize the kernel memory interface */
509 if (machine_init(&statics) == -1)
514 /* determine sorting order index, if necessary */
515 if (order_name != NULL)
517 if ((order_index = string_index(order_name, statics.order_names)) == -1)
519 const char * const *pp;
521 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
523 fprintf(stderr, "\tTry one of these:");
524 pp = statics.order_names;
527 fprintf(stderr, " %s", *pp++);
534 /* initialize termcap */
535 init_termcap(interactive);
537 /* get the string to use for the process area header */
538 header_text = format_header(uname_field);
540 /* initialize display interface */
541 if ((max_topn = display_init(&statics)) == -1)
543 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
547 /* print warning if user requested more processes than we can display */
551 "%s: warning: this terminal can only display %d processes.\n",
556 /* adjust for topn == Infinity */
557 if (topn == Infinity)
560 * For smart terminals, infinity really means everything that can
561 * be displayed, or Largest.
562 * On dumb terminals, infinity means every process in the system!
563 * We only really want to do that if it was explicitly specified.
564 * This is always the case when "Default_TOPN != Infinity". But if
565 * topn wasn't explicitly specified and we are on a dumb terminal
566 * and the default is Infinity, then (and only then) we use
567 * "Nominal_TOPN" instead.
569 topn = smart_terminal ? Largest :
570 (topn_specified ? Largest : Nominal_TOPN);
573 /* set header display accordingly */
574 display_header(topn > 0);
576 /* determine interactive state */
577 if (interactive == 2)
579 interactive = smart_terminal;
582 /* if # of displays not specified, fill it in */
585 displays = smart_terminal ? Infinity : 1;
588 /* hold interrupt signals while setting up the screen and the handlers */
590 sigemptyset(&new_sigmask);
591 sigaddset(&new_sigmask, SIGINT);
592 sigaddset(&new_sigmask, SIGQUIT);
593 sigaddset(&new_sigmask, SIGTSTP);
594 sigprocmask(SIG_BLOCK, &new_sigmask, &old_sigmask);
596 signal(SIGINT, leave);
597 signal(SIGQUIT, leave);
598 signal(SIGTSTP, tstop);
599 signal(SIGWINCH, top_winch);
600 sigprocmask(SIG_SETMASK, &old_sigmask, NULL);
603 fputs("....", stderr);
612 * main loop -- repeat while display count is positive or while it
613 * indicates infinity (by being -1)
616 while ((displays == -1) || (displays-- > 0))
618 int (*compare)(const void * const, const void * const);
621 /* get the current stats */
622 get_system_info(&system_info);
624 compare = compares[order_index];
626 /* get the current set of processes */
628 get_process_info(&system_info, &ps, compare);
630 /* display the load averages */
631 (*d_loadave)(system_info.last_pid,
632 system_info.load_avg);
634 /* display the current time */
635 /* this method of getting the time SHOULD be fairly portable */
637 i_uptime(&system_info.boottime, &curr_time);
638 i_timeofday(&curr_time);
640 /* display process state breakdown */
641 (*d_procstates)(system_info.p_total,
642 system_info.procstates);
643 (*d_cpustates)(system_info.cpustates);
645 /* display memory stats */
646 (*d_memory)(system_info.memory);
647 (*d_arc)(system_info.arc);
648 (*d_carc)(system_info.carc);
650 /* display swap stats */
651 (*d_swap)(system_info.swap);
653 /* handle message area */
656 /* update the header area */
657 (*d_header)(header_text);
661 /* determine number of processes to actually display */
662 /* this number will be the smallest of: active processes,
663 number user requested, number current screen accomodates */
664 active_procs = system_info.p_pactive;
665 if (active_procs > topn)
669 if (active_procs > max_topn)
671 active_procs = max_topn;
674 /* now show the top "n" processes. */
675 for (i = 0; i < active_procs; i++)
677 (*d_process)(i, format_next_process(processes, get_userid,
686 /* do end-screen processing */
689 /* now, flush the output buffer */
690 if (fflush(stdout) != 0)
692 new_message(MT_standout, " Write error on stdout");
697 /* only do the rest if we have more displays to show */
700 /* switch out for new display on smart terminals */
709 d_loadave = u_loadave;
710 d_procstates = u_procstates;
711 d_cpustates = u_cpustates;
716 d_message = u_message;
718 d_process = u_process;
731 else while (no_command)
733 /* assume valid command unless told otherwise */
736 /* set up arguments for select with timeout */
738 FD_SET(0, &readfds); /* for standard input */
739 timeout.tv_sec = delay;
748 /* move to the lower left */
752 /* default the signal handler action */
753 signal(SIGTSTP, SIG_DFL);
755 /* unblock the signal and send ourselves one */
756 sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
759 /* reset the signal handler */
760 signal(SIGTSTP, tstop);
770 /* reascertain the screen dimensions */
773 /* tell display to resize */
774 max_topn = display_resize();
776 /* reset the signal handler */
777 signal(SIGWINCH, top_winch);
784 /* wait for either input or the end of the delay period */
785 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
786 if (sel_ret < 0 && errno != EINTR)
792 const struct command *cptr;
794 /* something to read -- clear the message area first */
797 /* now read it and convert to command strchr */
798 /* (use "change" as a temporary to hold strchr) */
799 if (read(0, &ch, 1) != 1)
801 /* read error: either 0 or -1 */
802 new_message(MT_standout, " Read error on stdin");
806 if (ch == '\r' || ch == '\n') {
810 while (cptr->c != '\0') {
816 if (cptr->c == '\0') {
817 new_message(MT_standout, " Command not understood");
821 if (overstrike && !cptr->available_to_dumb)
823 new_message(MT_standout,
824 " Command cannot be handled by this terminal");
831 case CMD_redraw: /* redraw screen */
835 case CMD_update: /* merely update display */
846 top_standout("Hit any key to continue: ");
851 case CMD_errors: /* show errors */
852 if (error_count() == 0)
854 new_message(MT_standout,
855 " Currently no errors to report.");
864 top_standout("Hit any key to continue: ");
871 new_message(MT_standout,
872 "Number of processes to show: ");
873 newval = readline(tempbuf1, 8, true);
876 if (newval > max_topn)
878 new_message(MT_standout | MT_delayed,
879 " This terminal can only display %d processes.",
886 /* inhibit the header */
887 display_header(false);
889 else if (newval > topn && topn == 0)
891 /* redraw the header */
892 display_header(true);
899 case CMD_delay: /* new seconds delay */
900 new_message(MT_standout, "Seconds to delay: ");
901 if ((i = readline(tempbuf1, 8, true)) > -1)
903 if ((delay = i) == 0)
911 case CMD_displays: /* change display count */
912 new_message(MT_standout,
913 "Displays to show (currently %s): ",
914 displays == -1 ? "infinite" :
916 if ((i = readline(tempbuf1, 10, true)) > 0)
927 case CMD_kill: /* kill program */
928 new_message(0, "kill ");
929 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
931 if ((errmsg = kill_procs(tempbuf2)) != NULL)
933 new_message(MT_standout, "%s", errmsg);
944 case CMD_renice: /* renice program */
945 new_message(0, "renice ");
946 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
948 if ((errmsg = renice_procs(tempbuf2)) != NULL)
950 new_message(MT_standout, "%s", errmsg);
963 new_message(MT_standout | MT_delayed,
964 " %sisplaying idle processes.",
965 ps.idle ? "D" : "Not d");
971 new_message(MT_standout | MT_delayed,
972 " %sisplaying self.",
973 (ps.self) ? "D" : "Not d");
978 if (handle_user(tempbuf2, sizeof(tempbuf2)))
983 ps.thread = !ps.thread;
984 new_message(MT_standout | MT_delayed,
985 " Displaying threads %s",
986 ps.thread ? "separately" : "as a count");
987 header_text = format_header(uname_field);
993 ps.thread_id = !ps.thread_id;
994 new_message(MT_standout | MT_delayed,
996 ps.thread_id ? "tid" : "pid");
997 header_text = format_header(uname_field);
1004 new_message(MT_standout | MT_delayed,
1005 " Displaying %s CPU",
1006 ps.wcpu ? "weighted" : "raw");
1007 header_text = format_header(uname_field);
1012 displaymode = displaymode == DISP_IO ? DISP_CPU : DISP_IO;
1013 header_text = format_header(uname_field);
1014 display_header(true);
1015 d_header = i_header;
1019 ps.system = !ps.system;
1022 fmt_flags ^= FMT_SHOWARGS;
1025 new_message(MT_standout,
1027 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
1029 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1031 new_message(MT_standout,
1032 " %s: unrecognized sorting order", tempbuf2);
1048 new_message(MT_standout | MT_delayed,
1049 " %sisplaying jail ID.",
1050 ps.jail ? "D" : "Not d");
1051 header_text = format_header(uname_field);
1057 new_message(MT_standout,
1058 "Jail to show (+ for all): ");
1059 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
1061 if (tempbuf2[0] == '+' &&
1062 tempbuf2[1] == '\0')
1066 else if ((i = jail_getid(tempbuf2)) == -1)
1068 new_message(MT_standout,
1069 " %s: unknown jail", tempbuf2);
1078 new_message(MT_standout |
1079 MT_delayed, " Displaying jail "
1082 format_header(uname_field);
1094 ps.kidle = !ps.kidle;
1095 new_message(MT_standout | MT_delayed,
1096 " %sisplaying system idle process.",
1097 ps.kidle ? "D" : "Not d");
1101 pcpu_stats = !pcpu_stats;
1102 new_message(MT_standout | MT_delayed,
1103 " Displaying %sCPU statistics.",
1104 pcpu_stats ? "per-" : "global ");
1106 max_topn = display_updatecpus(&statics);
1112 new_message(MT_standout | MT_delayed,
1113 " %sisplaying per-process swap usage.",
1114 ps.swap ? "D" : "Not d");
1115 header_text = format_header(uname_field);
1120 new_message(MT_standout,
1121 "Process id to show (+ for all): ");
1122 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0) {
1123 if (tempbuf2[0] == '+' &&
1124 tempbuf2[1] == '\0') {
1127 unsigned long long num;
1130 num = strtonum(tempbuf2, 0, INT_MAX,
1132 if (errstr != NULL || !find_pid(num)) {
1133 new_message(MT_standout,
1138 ps.pid = (pid_t)num;
1146 assert(false && "reached switch without command");
1151 /* flush out stuff that may have been written */
1164 * reset_display() - reset all the display routine pointers so that entire
1165 * screen will get redrawn.
1171 d_loadave = i_loadave;
1172 d_procstates = i_procstates;
1173 d_cpustates = i_cpustates;
1174 d_memory = i_memory;
1178 d_message = i_message;
1179 d_header = i_header;
1180 d_process = i_process;
1188 leave(int i __unused) /* exit under normal conditions -- INT handler */
1195 tstop(int i __unused) /* SIGTSTP handler */
1202 top_winch(int i __unused) /* SIGWINCH handler */
1209 quit(int status) /* exit under duress */