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' }
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;
258 /* set the buffer for stdout */
261 debug = fopen("debug.run", "w");
262 setbuffer(stdout, NULL, 0);
264 setbuffer(stdout, stdoutbuf, Buffersize);
270 /* initialize some selection options */
283 ps.thread_id = false;
285 /* get preset options from the environment */
286 if ((env_top = getenv("TOP")) != NULL)
288 av = preset_argv = argparse(env_top, &preset_argc);
291 /* set the dummy argument to an explanatory message, in case
292 getopt encounters a bad argument */
293 preset_argv[0] = "while processing environment";
296 /* process options */
298 /* if we're done doing the presets, then process the real arguments */
299 if (preset_argc == 0)
304 /* this should keep getopt happy... */
308 while ((i = getopt_long(ac, av, "CSIHPabijJ:nquvzs:d:U:m:o:p:Ttw", longopts, NULL)) != EOF)
312 case 'v': /* show version number */
313 errx(0, "version FreeBSD");
316 case 'u': /* toggle uid/username display */
317 do_unames = !do_unames;
320 case 'U': /* display only username's processes */
321 if ((ps.uid[0] = userid(optarg)) == -1)
323 errx(1, "%s: unknown user\n", optarg);
327 case 'S': /* show system processes */
331 case 'I': /* show idle processes */
335 case 'i': /* go interactive regardless */
339 case 'n': /* batch, or non-interactive */
345 fmt_flags ^= FMT_SHOWARGS;
348 case 'd': /* number of displays to show */
349 if ((i = atoiwi(optarg)) == Invalid || i == 0)
351 warnx("warning: display count should be positive -- option ignored");
360 unsigned long long num;
363 num = strtonum(optarg, 0, INT_MAX, &errstr);
364 if (errstr != NULL || !find_pid(num)) {
365 fprintf(stderr, "%s: unknown pid\n", optarg);
374 delay = strtod(optarg, &nptr);
375 if (nptr == optarg) {
376 warnx("warning: invalid delay");
381 warnx("warning: seconds delay should be positive -- using default");
388 case 'q': /* be quick about it */
390 i = setpriority(PRIO_PROCESS, 0, PRIO_MIN);
391 if (i == -1 && errno != 0) {
392 warnx("warning: `-q' option failed (%m)");
397 case 'm': /* select display mode */
398 if (strcmp(optarg, "io") == 0) {
399 displaymode = DISP_IO;
400 } else if (strcmp(optarg, "cpu") == 0) {
401 displaymode = DISP_CPU;
403 errx(1, "warning: `-m' option can only take args 'io' or 'cpu'");
407 case 'o': /* select sort order */
420 ps.thread = !ps.thread;
424 ps.thread_id = !ps.thread_id;
431 case 'J': /* display only jail's processes */
432 if ((ps.jid = jail_getid(optarg)) == -1)
434 fprintf(stderr, "%s: unknown jail\n", optarg);
441 pcpu_stats = !pcpu_stats;
449 ps.kidle = !ps.kidle;
454 "[-abCHIijnPqStuvwz] [-d count] [-m io | cpu] [-o field] [-p pid]\n"
455 " [-s time] [-J jail] [-U username] [number]");
459 /* get count of top processes to display (if any) */
462 if ((topn = atoiwi(av[optind])) == Invalid)
464 warnx("warning: process display count should be non-negative -- using default");
469 topn_specified = true;
473 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
477 /* repeat only if we really did the preset arguments */
480 /* set constants for username/uid display correctly */
483 uname_field = " UID ";
487 /* initialize the kernel memory interface */
488 if (machine_init(&statics) == -1)
493 /* determine sorting order index, if necessary */
494 if (order_name != NULL)
496 if ((order_index = string_index(order_name, statics.order_names)) == -1)
498 const char * const *pp;
500 warnx("'%s' is not a recognized sorting order.", order_name);
501 fprintf(stderr, "\tTry one of these:");
502 pp = statics.order_names;
505 fprintf(stderr, " %s", *pp++);
512 /* initialize termcap */
513 init_termcap(interactive);
515 /* get the string to use for the process area header */
516 header_text = format_header(uname_field);
518 /* initialize display interface */
519 if ((max_topn = display_init(&statics)) == -1)
521 errx(4, "can't allocate sufficient memory");
524 /* print warning if user requested more processes than we can display */
527 warnx("warning: this terminal can only display %d processes.", max_topn);
531 /* adjust for topn == Infinity */
532 if (topn == Infinity)
535 * For smart terminals, infinity really means everything that can
536 * be displayed, or Largest.
537 * On dumb terminals, infinity means every process in the system!
538 * We only really want to do that if it was explicitly specified.
539 * This is always the case when "Default_TOPN != Infinity". But if
540 * topn wasn't explicitly specified and we are on a dumb terminal
541 * and the default is Infinity, then (and only then) we use
542 * "Nominal_TOPN" instead.
544 topn = smart_terminal ? Largest :
545 (topn_specified ? Largest : Nominal_TOPN);
548 /* set header display accordingly */
549 display_header(topn > 0);
551 /* determine interactive state */
552 if (interactive == 2)
554 interactive = smart_terminal;
557 /* if # of displays not specified, fill it in */
560 displays = smart_terminal ? Infinity : 1;
563 /* hold interrupt signals while setting up the screen and the handlers */
565 sigemptyset(&new_sigmask);
566 sigaddset(&new_sigmask, SIGINT);
567 sigaddset(&new_sigmask, SIGQUIT);
568 sigaddset(&new_sigmask, SIGTSTP);
569 sigprocmask(SIG_BLOCK, &new_sigmask, &old_sigmask);
571 signal(SIGINT, leave);
572 signal(SIGQUIT, leave);
573 signal(SIGTSTP, tstop);
574 signal(SIGWINCH, top_winch);
575 sigprocmask(SIG_SETMASK, &old_sigmask, NULL);
578 fputs("....", stderr);
587 * main loop -- repeat while display count is positive or while it
588 * indicates infinity (by being -1)
591 while ((displays == -1) || (displays-- > 0))
593 int (*compare)(const void * const, const void * const);
596 /* get the current stats */
597 get_system_info(&system_info);
599 compare = compares[order_index];
601 /* get the current set of processes */
603 get_process_info(&system_info, &ps, compare);
605 /* display the load averages */
606 (*d_loadave)(system_info.last_pid,
607 system_info.load_avg);
609 /* display the current time */
610 /* this method of getting the time SHOULD be fairly portable */
612 i_uptime(&system_info.boottime, &curr_time);
613 i_timeofday(&curr_time);
615 /* display process state breakdown */
616 (*d_procstates)(system_info.p_total,
617 system_info.procstates);
618 (*d_cpustates)(system_info.cpustates);
620 /* display memory stats */
621 (*d_memory)(system_info.memory);
622 (*d_arc)(system_info.arc);
623 (*d_carc)(system_info.carc);
625 /* display swap stats */
626 (*d_swap)(system_info.swap);
628 /* handle message area */
631 /* update the header area */
632 (*d_header)(header_text);
636 /* determine number of processes to actually display */
637 /* this number will be the smallest of: active processes,
638 number user requested, number current screen accomodates */
639 active_procs = system_info.p_pactive;
640 if (active_procs > topn)
644 if (active_procs > max_topn)
646 active_procs = max_topn;
649 /* now show the top "n" processes. */
650 for (i = 0; i < active_procs; i++)
652 (*d_process)(i, format_next_process(processes, get_userid,
661 /* do end-screen processing */
664 /* now, flush the output buffer */
665 if (fflush(stdout) != 0)
667 new_message(MT_standout, " Write error on stdout");
672 /* only do the rest if we have more displays to show */
675 /* switch out for new display on smart terminals */
684 d_loadave = u_loadave;
685 d_procstates = u_procstates;
686 d_cpustates = u_cpustates;
691 d_message = u_message;
693 d_process = u_process;
706 else while (no_command)
708 /* assume valid command unless told otherwise */
711 /* set up arguments for select with timeout */
713 FD_SET(0, &readfds); /* for standard input */
714 timeout.tv_sec = delay;
723 /* move to the lower left */
727 /* default the signal handler action */
728 signal(SIGTSTP, SIG_DFL);
730 /* unblock the signal and send ourselves one */
731 sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
734 /* reset the signal handler */
735 signal(SIGTSTP, tstop);
745 /* reascertain the screen dimensions */
748 /* tell display to resize */
749 max_topn = display_resize();
751 /* reset the signal handler */
752 signal(SIGWINCH, top_winch);
759 /* wait for either input or the end of the delay period */
760 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
761 if (sel_ret < 0 && errno != EINTR)
767 const struct command *cptr;
769 /* something to read -- clear the message area first */
772 /* now read it and convert to command strchr */
773 /* (use "change" as a temporary to hold strchr) */
774 if (read(0, &ch, 1) != 1)
776 /* read error: either 0 or -1 */
777 new_message(MT_standout, " Read error on stdin");
781 if (ch == '\r' || ch == '\n') {
785 while (cptr->c != '\0') {
791 if (cptr->c == '\0') {
792 new_message(MT_standout, " Command not understood");
796 if (overstrike && !cptr->available_to_dumb)
798 new_message(MT_standout,
799 " Command cannot be handled by this terminal");
806 case CMD_redraw: /* redraw screen */
810 case CMD_update: /* merely update display */
821 top_standout("Hit any key to continue: ");
826 case CMD_errors: /* show errors */
827 if (error_count() == 0)
829 new_message(MT_standout,
830 " Currently no errors to report.");
839 top_standout("Hit any key to continue: ");
846 new_message(MT_standout,
847 "Number of processes to show: ");
848 newval = readline(tempbuf1, 8, true);
851 if (newval > max_topn)
853 new_message(MT_standout | MT_delayed,
854 " This terminal can only display %d processes.",
861 /* inhibit the header */
862 display_header(false);
864 else if (newval > topn && topn == 0)
866 /* redraw the header */
867 display_header(true);
874 case CMD_delay: /* new seconds delay */
875 new_message(MT_standout, "Seconds to delay: ");
876 if ((i = readline(tempbuf1, 8, true)) > -1)
878 if ((delay = i) == 0)
886 case CMD_displays: /* change display count */
887 new_message(MT_standout,
888 "Displays to show (currently %s): ",
889 displays == -1 ? "infinite" :
891 if ((i = readline(tempbuf1, 10, true)) > 0)
902 case CMD_kill: /* kill program */
903 new_message(0, "kill ");
904 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
906 if ((errmsg = kill_procs(tempbuf2)) != NULL)
908 new_message(MT_standout, "%s", errmsg);
919 case CMD_renice: /* renice program */
920 new_message(0, "renice ");
921 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
923 if ((errmsg = renice_procs(tempbuf2)) != NULL)
925 new_message(MT_standout, "%s", errmsg);
938 new_message(MT_standout | MT_delayed,
939 " %sisplaying idle processes.",
940 ps.idle ? "D" : "Not d");
946 new_message(MT_standout | MT_delayed,
947 " %sisplaying self.",
948 (ps.self) ? "D" : "Not d");
953 if (handle_user(tempbuf2, sizeof(tempbuf2)))
958 ps.thread = !ps.thread;
959 new_message(MT_standout | MT_delayed,
960 " Displaying threads %s",
961 ps.thread ? "separately" : "as a count");
962 header_text = format_header(uname_field);
968 ps.thread_id = !ps.thread_id;
969 new_message(MT_standout | MT_delayed,
971 ps.thread_id ? "tid" : "pid");
972 header_text = format_header(uname_field);
979 new_message(MT_standout | MT_delayed,
980 " Displaying %s CPU",
981 ps.wcpu ? "weighted" : "raw");
982 header_text = format_header(uname_field);
987 displaymode = displaymode == DISP_IO ? DISP_CPU : DISP_IO;
988 new_message(MT_standout | MT_delayed,
989 " Displaying %s statistics.",
990 displaymode == DISP_IO ? "IO" : "CPU");
991 header_text = format_header(uname_field);
992 display_header(true);
997 ps.system = !ps.system;
998 new_message(MT_standout | MT_delayed,
999 " %sisplaying system processes.",
1000 ps.system ? "D" : "Not d");
1003 fmt_flags ^= FMT_SHOWARGS;
1004 new_message(MT_standout | MT_delayed,
1005 " %sisplaying process arguments.",
1006 fmt_flags & FMT_SHOWARGS ? "D" : "Not d");
1009 new_message(MT_standout,
1011 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
1013 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1015 new_message(MT_standout,
1016 " %s: unrecognized sorting order", tempbuf2);
1032 new_message(MT_standout | MT_delayed,
1033 " %sisplaying jail ID.",
1034 ps.jail ? "D" : "Not d");
1035 header_text = format_header(uname_field);
1041 new_message(MT_standout,
1042 "Jail to show (+ for all): ");
1043 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0)
1045 if (tempbuf2[0] == '+' &&
1046 tempbuf2[1] == '\0')
1050 else if ((i = jail_getid(tempbuf2)) == -1)
1052 new_message(MT_standout,
1053 " %s: unknown jail", tempbuf2);
1062 new_message(MT_standout |
1063 MT_delayed, " Displaying jail "
1066 format_header(uname_field);
1078 ps.kidle = !ps.kidle;
1079 new_message(MT_standout | MT_delayed,
1080 " %sisplaying system idle process.",
1081 ps.kidle ? "D" : "Not d");
1085 pcpu_stats = !pcpu_stats;
1086 new_message(MT_standout | MT_delayed,
1087 " Displaying %sCPU statistics.",
1088 pcpu_stats ? "per-" : "global ");
1090 max_topn = display_updatecpus(&statics);
1096 new_message(MT_standout | MT_delayed,
1097 " %sisplaying per-process swap usage.",
1098 ps.swap ? "D" : "Not d");
1099 header_text = format_header(uname_field);
1104 new_message(MT_standout,
1105 "Process id to show (+ for all): ");
1106 if (readline(tempbuf2, sizeof(tempbuf2), false) > 0) {
1107 if (tempbuf2[0] == '+' &&
1108 tempbuf2[1] == '\0') {
1111 unsigned long long num;
1114 num = strtonum(tempbuf2, 0, INT_MAX,
1116 if (errstr != NULL || !find_pid(num)) {
1117 new_message(MT_standout,
1122 ps.pid = (pid_t)num;
1130 assert(false && "reached switch without command");
1135 /* flush out stuff that may have been written */
1148 * reset_display() - reset all the display routine pointers so that entire
1149 * screen will get redrawn.
1155 d_loadave = i_loadave;
1156 d_procstates = i_procstates;
1157 d_cpustates = i_cpustates;
1158 d_memory = i_memory;
1162 d_message = i_message;
1163 d_header = i_header;
1164 d_process = i_process;
1172 leave(int i __unused) /* exit under normal conditions -- INT handler */
1179 tstop(int i __unused) /* SIGTSTP handler */
1186 top_winch(int i __unused) /* SIGWINCH handler */
1193 quit(int status) /* exit under duress */