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>
37 #include "display.h" /* interface to display package */
38 #include "screen.h" /* interface to screen package */
44 /* Size of the stdio buffer given to stdout */
45 #define Buffersize 2048
48 "Copyright (c) 1984 through 1996, William LeFebvre";
50 typedef void sigret_t;
52 /* The buffer that stdio will use */
53 static char stdoutbuf[Buffersize];
55 static int fmt_flags = 0;
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);
269 if (setlocale(LC_ALL, "") == NULL) {
270 fprintf(stderr, "invalid locale.\n");
277 /* initialize some selection options */
290 ps.thread_id = false;
292 /* get preset options from the environment */
293 if ((env_top = getenv("TOP")) != NULL)
295 av = preset_argv = argparse(env_top, &preset_argc);
298 /* set the dummy argument to an explanatory message, in case
299 getopt encounters a bad argument */
300 preset_argv[0] = "while processing environment";
303 /* process options */
305 /* if we're done doing the presets, then process the real arguments */
306 if (preset_argc == 0)
311 /* this should keep getopt happy... */
315 while ((i = getopt_long(ac, __DECONST(char * const *, av), "CSIHPabijJ:nquvzs:d:U:m:o:p:Ttw", longopts, NULL)) != EOF)
319 case 'v': /* show version number */
320 errx(0, "version FreeBSD");
323 case 'u': /* toggle uid/username display */
324 do_unames = !do_unames;
327 case 'U': /* display only username's processes */
328 if ((ps.uid[0] = userid(optarg)) == -1)
330 errx(1, "%s: unknown user\n", optarg);
334 case 'S': /* show system processes */
338 case 'I': /* show idle processes */
342 case 'i': /* go interactive regardless */
346 case 'n': /* batch, or non-interactive */
352 fmt_flags ^= FMT_SHOWARGS;
355 case 'd': /* number of displays to show */
356 if ((i = atoiwi(optarg)) == Invalid || i == 0)
358 warnx("warning: display count should be positive -- option ignored");
367 unsigned long long num;
370 num = strtonum(optarg, 0, INT_MAX, &errstr);
371 if (errstr != NULL || !find_pid(num)) {
372 fprintf(stderr, "%s: unknown pid\n", optarg);
382 double delay_d = strtod(optarg, &nptr);
385 warnx("warning: invalid delay");
388 else if (delay_d <= 0)
390 warnx("warning: seconds delay should be positive -- using default");
395 delay.tv_sec = delay_d;
396 delay.tv_usec = (delay_d - delay.tv_sec) * 1e6;
401 case 'q': /* be quick about it */
403 i = setpriority(PRIO_PROCESS, 0, PRIO_MIN);
404 if (i == -1 && errno != 0) {
405 warnx("warning: `-q' option failed (%m)");
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;
416 errx(1, "warning: `-m' option can only take args 'io' or 'cpu'");
420 case 'o': /* select sort order */
433 ps.thread = !ps.thread;
437 ps.thread_id = !ps.thread_id;
444 case 'J': /* display only jail's processes */
445 if ((ps.jid = jail_getid(optarg)) == -1)
447 fprintf(stderr, "%s: unknown jail\n", optarg);
454 pcpu_stats = !pcpu_stats;
462 ps.kidle = !ps.kidle;
467 "[-abCHIijnPqStuvwz] [-d count] [-m io | cpu] [-o field] [-p pid]\n"
468 " [-s time] [-J jail] [-U username] [number]");
472 /* get count of top processes to display (if any) */
475 if ((topn = atoiwi(av[optind])) == Invalid)
477 warnx("warning: process display count should be non-negative -- using default");
482 topn_specified = true;
486 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
490 /* repeat only if we really did the preset arguments */
493 /* set constants for username/uid display correctly */
496 uname_field = " UID ";
500 /* initialize the kernel memory interface */
501 if (machine_init(&statics) == -1)
506 /* determine sorting order index, if necessary */
507 if (order_name != NULL)
509 if ((order_index = string_index(order_name, statics.order_names)) == -1)
511 const char * const *pp;
513 warnx("'%s' is not a recognized sorting order.", order_name);
514 fprintf(stderr, "\tTry one of these:");
515 pp = statics.order_names;
518 fprintf(stderr, " %s", *pp++);
525 /* initialize termcap */
526 init_termcap(interactive);
528 /* get the string to use for the process area header */
529 header_text = format_header(uname_field);
531 /* initialize display interface */
532 if ((max_topn = display_init(&statics)) == -1)
534 errx(4, "can't allocate sufficient memory");
537 /* print warning if user requested more processes than we can display */
540 warnx("warning: this terminal can only display %d processes.", max_topn);
544 /* adjust for topn == Infinity */
545 if (topn == Infinity)
548 * For smart terminals, infinity really means everything that can
549 * be displayed, or Largest.
550 * On dumb terminals, infinity means every process in the system!
551 * We only really want to do that if it was explicitly specified.
552 * This is always the case when "Default_TOPN != Infinity". But if
553 * topn wasn't explicitly specified and we are on a dumb terminal
554 * and the default is Infinity, then (and only then) we use
555 * "Nominal_TOPN" instead.
557 topn = smart_terminal ? Largest :
558 (topn_specified ? Largest : Nominal_TOPN);
561 /* set header display accordingly */
562 display_header(topn > 0);
564 /* determine interactive state */
565 if (interactive == 2)
567 interactive = smart_terminal;
570 /* if # of displays not specified, fill it in */
573 displays = smart_terminal ? Infinity : 1;
576 /* hold interrupt signals while setting up the screen and the handlers */
578 sigemptyset(&new_sigmask);
579 sigaddset(&new_sigmask, SIGINT);
580 sigaddset(&new_sigmask, SIGQUIT);
581 sigaddset(&new_sigmask, SIGTSTP);
582 sigprocmask(SIG_BLOCK, &new_sigmask, &old_sigmask);
584 signal(SIGINT, leave);
585 signal(SIGQUIT, leave);
586 signal(SIGTSTP, tstop);
587 signal(SIGWINCH, top_winch);
588 sigprocmask(SIG_SETMASK, &old_sigmask, NULL);
591 fputs("....", stderr);
600 * main loop -- repeat while display count is positive or while it
601 * indicates infinity (by being -1)
604 while ((displays == -1) || (displays-- > 0))
606 int (*compare)(const void * const, const void * const);
609 /* get the current stats */
610 get_system_info(&system_info);
612 compare = compares[order_index];
614 /* get the current set of processes */
616 get_process_info(&system_info, &ps, compare);
618 /* display the load averages */
619 (*d_loadave)(system_info.last_pid,
620 system_info.load_avg);
622 /* display the battery info (if any) */
623 i_battery(statics.nbatteries, system_info.battery);
625 /* display the current time */
626 /* this method of getting the time SHOULD be fairly portable */
628 i_uptime(&system_info.boottime, &curr_time);
629 i_timeofday(&curr_time);
631 /* display process state breakdown */
632 (*d_procstates)(system_info.p_total,
633 system_info.procstates);
634 (*d_cpustates)(system_info.cpustates);
636 /* display memory stats */
637 (*d_memory)(system_info.memory);
638 (*d_arc)(system_info.arc);
639 (*d_carc)(system_info.carc);
641 /* display swap stats */
642 (*d_swap)(system_info.swap);
644 /* handle message area */
647 /* update the header area */
648 (*d_header)(header_text);
652 /* determine number of processes to actually display */
653 /* this number will be the smallest of: active processes,
654 number user requested, number current screen accomodates */
655 active_procs = system_info.p_pactive;
656 if (active_procs > topn)
660 if (active_procs > max_topn)
662 active_procs = max_topn;
665 /* now show the top "n" processes. */
666 for (i = 0; i < active_procs; i++)
668 (*d_process)(i, format_next_process(processes, get_userid,
677 /* do end-screen processing */
680 /* now, flush the output buffer */
681 if (fflush(stdout) != 0)
683 new_message(MT_standout, " Write error on stdout");
688 /* only do the rest if we have more displays to show */
691 /* switch out for new display on smart terminals */
700 d_loadave = u_loadave;
701 d_procstates = u_procstates;
702 d_cpustates = u_cpustates;
707 d_message = u_message;
709 d_process = u_process;
717 select(0, NULL, NULL, NULL, &timeout);
723 else while (no_command)
725 /* assume valid command unless told otherwise */
728 /* set up arguments for select with timeout */
730 FD_SET(0, &readfds); /* for standard input */
739 /* move to the lower left */
743 /* default the signal handler action */
744 signal(SIGTSTP, SIG_DFL);
746 /* unblock the signal and send ourselves one */
747 sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
750 /* reset the signal handler */
751 signal(SIGTSTP, tstop);
761 /* reascertain the screen dimensions */
764 /* tell display to resize */
765 max_topn = display_resize();
767 /* reset the signal handler */
768 signal(SIGWINCH, top_winch);
775 /* wait for either input or the end of the delay period */
776 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
777 if (sel_ret < 0 && errno != EINTR)
783 const struct command *cptr;
785 /* something to read -- clear the message area first */
788 /* now read it and convert to command strchr */
789 /* (use "change" as a temporary to hold strchr) */
790 if (read(0, &ch, 1) != 1)
792 /* read error: either 0 or -1 */
793 new_message(MT_standout, " Read error on stdin");
797 if (ch == '\r' || ch == '\n') {
801 while (cptr->c != '\0') {
807 if (cptr->c == '\0') {
808 new_message(MT_standout, " Command not understood");
812 if (overstrike && !cptr->available_to_dumb)
814 new_message(MT_standout,
815 " Command cannot be handled by this terminal");
822 case CMD_redraw: /* redraw screen */
826 case CMD_update: /* merely update display */
837 top_standout("Hit any key to continue: ");
842 case CMD_errors: /* show errors */
843 if (error_count() == 0)
845 new_message(MT_standout,
846 " Currently no errors to report.");
855 top_standout("Hit any key to continue: ");
862 new_message(MT_standout,
863 "Number of processes to show: ");
864 newval = readline(tempbuf1, 8, true);
867 if (newval > max_topn)
869 new_message(MT_standout | MT_delayed,
870 " This terminal can only display %d processes.",
877 /* inhibit the header */
878 display_header(false);
880 else if (newval > topn && topn == 0)
882 /* redraw the header */
883 display_header(true);
890 case CMD_delay: /* new seconds delay */
891 new_message(MT_standout, "Seconds to delay: ");
892 if ((i = readline(tempbuf1, 8, false)) > 0)
894 double delay_d = strtod(tempbuf1, &nptr);
895 if (nptr == tempbuf1 || delay_d <= 0)
897 new_message(MT_standout, " Invalid delay");
903 delay.tv_sec = delay_d;
904 delay.tv_usec = (delay_d - delay.tv_sec) * 1e6;
910 case CMD_displays: /* change display count */
911 new_message(MT_standout,
912 "Displays to show (currently %s): ",
913 displays == -1 ? "infinite" :
915 if ((i = readline(tempbuf1, 10, true)) > 0)
926 case CMD_kill: /* kill program */
927 new_message(0, "kill ");
928 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
930 if ((errmsg = kill_procs(tempbuf2)) != NULL)
932 new_message(MT_standout, "%s", errmsg);
943 case CMD_renice: /* renice program */
944 new_message(0, "renice ");
945 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
947 if ((errmsg = renice_procs(tempbuf2)) != NULL)
949 new_message(MT_standout, "%s", errmsg);
962 new_message(MT_standout | MT_delayed,
963 " %sisplaying idle processes.",
964 ps.idle ? "D" : "Not d");
970 new_message(MT_standout | MT_delayed,
971 " %sisplaying self.",
972 (ps.self) ? "D" : "Not d");
977 if (handle_user(tempbuf2, sizeof(tempbuf2)))
982 ps.thread = !ps.thread;
983 new_message(MT_standout | MT_delayed,
984 " Displaying threads %s",
985 ps.thread ? "separately" : "as a count");
986 header_text = format_header(uname_field);
992 ps.thread_id = !ps.thread_id;
993 new_message(MT_standout | MT_delayed,
995 ps.thread_id ? "tid" : "pid");
996 header_text = format_header(uname_field);
1003 new_message(MT_standout | MT_delayed,
1004 " Displaying %s CPU",
1005 ps.wcpu ? "weighted" : "raw");
1006 header_text = format_header(uname_field);
1011 displaymode = displaymode == DISP_IO ? DISP_CPU : DISP_IO;
1012 new_message(MT_standout | MT_delayed,
1013 " Displaying %s statistics.",
1014 displaymode == DISP_IO ? "IO" : "CPU");
1015 header_text = format_header(uname_field);
1016 display_header(true);
1017 d_header = i_header;
1021 ps.system = !ps.system;
1022 new_message(MT_standout | MT_delayed,
1023 " %sisplaying system processes.",
1024 ps.system ? "D" : "Not d");
1027 fmt_flags ^= FMT_SHOWARGS;
1028 new_message(MT_standout | MT_delayed,
1029 " %sisplaying process arguments.",
1030 fmt_flags & FMT_SHOWARGS ? "D" : "Not d");
1033 new_message(MT_standout,
1035 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
1037 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1039 new_message(MT_standout,
1040 " %s: unrecognized sorting order", tempbuf2);
1056 new_message(MT_standout | MT_delayed,
1057 " %sisplaying jail ID.",
1058 ps.jail ? "D" : "Not d");
1059 header_text = format_header(uname_field);
1065 new_message(MT_standout,
1066 "Jail to show (+ for all): ");
1067 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
1069 if (tempbuf2[0] == '+' &&
1070 tempbuf2[1] == '\0')
1074 else if ((i = jail_getid(tempbuf2)) == -1)
1076 new_message(MT_standout,
1077 " %s: unknown jail", tempbuf2);
1086 new_message(MT_standout |
1087 MT_delayed, " Displaying jail "
1090 format_header(uname_field);
1102 ps.kidle = !ps.kidle;
1103 new_message(MT_standout | MT_delayed,
1104 " %sisplaying system idle process.",
1105 ps.kidle ? "D" : "Not d");
1109 pcpu_stats = !pcpu_stats;
1110 new_message(MT_standout | MT_delayed,
1111 " Displaying %sCPU statistics.",
1112 pcpu_stats ? "per-" : "global ");
1114 max_topn = display_updatecpus(&statics);
1120 new_message(MT_standout | MT_delayed,
1121 " %sisplaying per-process swap usage.",
1122 ps.swap ? "D" : "Not d");
1123 header_text = format_header(uname_field);
1128 new_message(MT_standout,
1129 "Process id to show (+ for all): ");
1130 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0) {
1131 if (tempbuf2[0] == '+' &&
1132 tempbuf2[1] == '\0') {
1135 unsigned long long num;
1138 num = strtonum(tempbuf2, 0, INT_MAX,
1140 if (errstr != NULL || !find_pid(num)) {
1141 new_message(MT_standout,
1146 ps.pid = (pid_t)num;
1154 assert(false && "reached switch without command");
1159 /* flush out stuff that may have been written */
1172 * reset_display() - reset all the display routine pointers so that entire
1173 * screen will get redrawn.
1179 d_loadave = i_loadave;
1180 d_procstates = i_procstates;
1181 d_cpustates = i_cpustates;
1182 d_memory = i_memory;
1186 d_message = i_message;
1187 d_header = i_header;
1188 d_process = i_process;
1196 leave(int i __unused) /* exit under normal conditions -- INT handler */
1203 tstop(int i __unused) /* SIGTSTP handler */
1210 top_winch(int i __unused) /* SIGWINCH handler */
1217 quit(int status) /* exit under duress */