2 "Copyright (c) 1984 through 1996, William LeFebvre";
5 * Top users/processes display for Unix
8 * This program may be freely redistributed,
9 * but this entire comment MUST remain intact.
11 * Copyright (c) 1984, 1989, William LeFebvre, Rice University
12 * Copyright (c) 1989 - 1994, William LeFebvre, Northwestern University
13 * Copyright (c) 1994, 1995, William LeFebvre, Argonne National Laboratory
14 * Copyright (c) 1996, William LeFebvre, Group sys Consulting
20 * See the file "Changes" for information on version-to-version changes.
24 * This file contains "main" and other high-level routines.
28 * The following preprocessor variables, when defined, are used to
29 * distinguish between different Unix implementations:
31 * SIGHOLD - use SVR4 sighold function when defined
32 * SIGRELSE - use SVR4 sigrelse function when defined
33 * FD_SET - macros FD_SET and FD_ZERO are used when defined
48 /* includes specific to top */
50 #include "display.h" /* interface to display package */
51 #include "screen.h" /* interface to screen package */
53 #include "top.local.h"
59 /* Size of the stdio buffer given to stdout */
60 #define Buffersize 2048
62 /* The buffer that stdio will use */
63 char stdoutbuf[Buffersize];
65 /* build Signal masks */
66 #define Smask(s) (1 << ((s) - 1))
72 /* imported from screen.c */
73 extern int overstrike;
75 static int fmt_flags = 0;
78 /* signal handling routines */
85 volatile sig_atomic_t leaveflag;
86 volatile sig_atomic_t tstopflag;
87 volatile sig_atomic_t winchflag;
89 /* internal routines */
92 /* values which need to be accessed by signal handlers */
93 static int max_topn; /* maximum displayable processes */
95 /* miscellaneous things */
96 struct process_select ps;
100 /* routines that don't return int */
105 char *renice_procs();
108 extern int (*compares[])();
110 extern int proc_compare();
111 extern int io_compare();
115 caddr_t get_process_info(struct system_info *si, struct process_select *sel,
116 int (*compare)(const void *, const void *));
118 /* different routines for displaying the user's identification */
119 /* (values assigned to get_userid) */
123 /* pointers to display routines */
124 void (*d_loadave)(int mpid, double *avenrun) = i_loadave;
125 void (*d_procstates)(int total, int *brkdn) = i_procstates;
126 void (*d_cpustates)(int *states) = i_cpustates;
127 void (*d_memory)(int *stats) = i_memory;
128 void (*d_arc)(int *stats) = i_arc;
129 void (*d_carc)(int *stats) = i_carc;
130 void (*d_swap)(int *stats) = i_swap;
131 void (*d_message)(void) = i_message;
132 void (*d_header)(char *text) = i_header;
133 void (*d_process)(int line, char *thisline) = i_process;
135 void reset_display(void);
146 register int active_procs;
149 struct system_info system_info;
150 struct statics statics;
153 static char tempbuf1[50];
154 static char tempbuf2[50];
155 int old_sigmask; /* only used for BSD-style signals */
156 int topn = Default_TOPN;
157 int delay = Default_DELAY;
158 int displays = 0; /* indicates unspecified */
161 char *(*get_userid)() = username;
162 char *uname_field = "USERNAME";
170 char do_unames = Yes;
171 char interactive = Maybe;
173 #if Default_TOPN == Infinity
174 char topn_specified = No;
179 struct timeval timeout;
181 char *order_name = NULL;
185 /* FD_SET and friends are not present: fake it */
187 #define FD_ZERO(x) (*(x) = 0)
188 #define FD_SET(f, x) (*(x) = 1<<f)
193 static char command_chars[] = "\f qh?en#sdkriIutHmSCajzPJwo";
195 static char command_chars[] = "\f qh?en#sdkriIutHmSCajzPJw";
197 /* these defines enumerate the "strchr"s of the commands in command_chars */
203 #define CMD_OSLIMIT 4 /* terminals with OS can only handle commands */
204 #define CMD_errors 5 /* less than or equal to CMD_OSLIMIT */
205 #define CMD_number1 6
206 #define CMD_number2 7
208 #define CMD_displays 9
210 #define CMD_renice 11
211 #define CMD_idletog 12
212 #define CMD_idletog2 13
214 #define CMD_selftog 15
215 #define CMD_thrtog 16
216 #define CMD_viewtog 17
217 #define CMD_viewsys 18
218 #define CMD_wcputog 19
219 #define CMD_showargs 20
220 #define CMD_jidtog 21
221 #define CMD_kidletog 22
222 #define CMD_pcputog 23
224 #define CMD_swaptog 25
229 /* set the buffer for stdout */
232 debug = fopen("debug.run", "w");
233 setbuffer(stdout, NULL, 0);
235 setbuffer(stdout, stdoutbuf, Buffersize);
241 if ((myname = strrchr(argv[0], '/')) == 0)
251 /* initialize some selection options */
264 /* get preset options from the environment */
265 if ((env_top = getenv("TOP")) != NULL)
267 av = preset_argv = argparse(env_top, &preset_argc);
270 /* set the dummy argument to an explanatory message, in case
271 getopt encounters a bad argument */
272 preset_argv[0] = "while processing environment";
275 /* process options */
277 /* if we're done doing the presets, then process the real arguments */
278 if (preset_argc == 0)
283 /* this should keep getopt happy... */
287 while ((i = getopt(ac, av, "CSIHPabijJ:nquvzs:d:U:m:o:tw")) != EOF)
291 case 'v': /* show version number */
292 fprintf(stderr, "%s: version %s\n",
293 myname, version_string());
297 case 'u': /* toggle uid/username display */
298 do_unames = !do_unames;
301 case 'U': /* display only username's processes */
302 if ((ps.uid = userid(optarg)) == -1)
304 fprintf(stderr, "%s: unknown user\n", optarg);
309 case 'S': /* show system processes */
310 ps.system = !ps.system;
313 case 'I': /* show idle processes */
317 case 'i': /* go interactive regardless */
321 case 'n': /* batch, or non-interactive */
327 fmt_flags ^= FMT_SHOWARGS;
330 case 'd': /* number of displays to show */
331 if ((i = atoiwi(optarg)) == Invalid || i == 0)
334 "%s: warning: display count should be positive -- option ignored\n",
345 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
348 "%s: warning: seconds delay should be positive -- using default\n",
350 delay = Default_DELAY;
355 case 'q': /* be quick about it */
356 /* only allow this if user is really root */
359 /* be very un-nice! */
365 "%s: warning: `-q' option can only be used by root\n",
371 case 'm': /* select display mode */
372 if (strcmp(optarg, "io") == 0) {
373 displaymode = DISP_IO;
374 } else if (strcmp(optarg, "cpu") == 0) {
375 displaymode = DISP_CPU;
378 "%s: warning: `-m' option can only take args "
385 case 'o': /* select sort order */
390 "%s: this platform does not support arbitrary ordering. Sorry.\n",
397 ps.self = (ps.self == -1) ? getpid() : -1;
405 ps.thread = !ps.thread;
412 case 'J': /* display only jail's processes */
413 if ((ps.jid = jail_getid(optarg)) == -1)
415 fprintf(stderr, "%s: unknown jail\n", optarg);
422 pcpu_stats = !pcpu_stats;
430 ps.kidle = !ps.kidle;
436 "Usage: %s [-abCHIijnPqStuvz] [-d count] [-m io | cpu] [-o field] [-s time]\n"
437 " [-J jail] [-U username] [number]\n",
438 version_string(), myname);
443 /* get count of top processes to display (if any) */
446 if ((topn = atoiwi(av[optind])) == Invalid)
449 "%s: warning: process display count should be non-negative -- using default\n",
453 #if Default_TOPN == Infinity
456 topn_specified = Yes;
461 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
465 /* repeat only if we really did the preset arguments */
468 /* set constants for username/uid display correctly */
471 uname_field = " UID ";
475 /* initialize the kernel memory interface */
476 if (machine_init(&statics, do_unames) == -1)
482 /* determine sorting order index, if necessary */
483 if (order_name != NULL)
485 if ((order_index = string_index(order_name, statics.order_names)) == -1)
489 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
491 fprintf(stderr, "\tTry one of these:");
492 pp = statics.order_names;
495 fprintf(stderr, " %s", *pp++);
503 #ifdef no_initialization_needed
504 /* initialize the hashing stuff */
511 /* initialize termcap */
512 init_termcap(interactive);
514 /* get the string to use for the process area header */
515 header_text = format_header(uname_field);
517 /* initialize display interface */
518 if ((max_topn = display_init(&statics)) == -1)
520 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
524 /* print warning if user requested more processes than we can display */
528 "%s: warning: this terminal can only display %d processes.\n",
533 /* adjust for topn == Infinity */
534 if (topn == Infinity)
537 * For smart terminals, infinity really means everything that can
538 * be displayed, or Largest.
539 * On dumb terminals, infinity means every process in the system!
540 * We only really want to do that if it was explicitly specified.
541 * This is always the case when "Default_TOPN != Infinity". But if
542 * topn wasn't explicitly specified and we are on a dumb terminal
543 * and the default is Infinity, then (and only then) we use
544 * "Nominal_TOPN" instead.
546 #if Default_TOPN == Infinity
547 topn = smart_terminal ? Largest :
548 (topn_specified ? Largest : Nominal_TOPN);
554 /* set header display accordingly */
555 display_header(topn > 0);
557 /* determine interactive state */
558 if (interactive == Maybe)
560 interactive = smart_terminal;
563 /* if # of displays not specified, fill it in */
566 displays = smart_terminal ? Infinity : 1;
569 /* hold interrupt signals while setting up the screen and the handlers */
575 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
578 (void) signal(SIGINT, leave);
579 (void) signal(SIGQUIT, leave);
580 (void) signal(SIGTSTP, tstop);
582 (void) signal(SIGWINCH, winch);
589 (void) sigsetmask(old_sigmask);
593 fputs("....", stderr);
594 fflush(stderr); /* why must I do this? */
595 sleep((unsigned)(3 * warnings));
602 * main loop -- repeat while display count is positive or while it
603 * indicates infinity (by being -1)
606 while ((displays == -1) || (displays-- > 0))
611 /* get the current stats */
612 get_system_info(&system_info);
615 compare = compares[order_index];
617 if (displaymode == DISP_CPU)
618 compare = proc_compare;
620 compare = io_compare;
623 /* get the current set of processes */
625 get_process_info(&system_info, &ps, compare);
627 /* display the load averages */
628 (*d_loadave)(system_info.last_pid,
629 system_info.load_avg);
631 /* display the current time */
632 /* this method of getting the time SHOULD be fairly portable */
634 i_uptime(&system_info.boottime, &curr_time);
635 i_timeofday(&curr_time);
637 /* display process state breakdown */
638 (*d_procstates)(system_info.p_total,
639 system_info.procstates);
641 /* display the cpu state percentage breakdown */
642 if (dostates) /* but not the first time */
644 (*d_cpustates)(system_info.cpustates);
648 /* we'll do it next time */
660 /* display memory stats */
661 (*d_memory)(system_info.memory);
662 (*d_arc)(system_info.arc);
663 (*d_carc)(system_info.carc);
665 /* display swap stats */
666 (*d_swap)(system_info.swap);
668 /* handle message area */
671 /* update the header area */
672 (*d_header)(header_text);
676 /* determine number of processes to actually display */
677 /* this number will be the smallest of: active processes,
678 number user requested, number current screen accomodates */
679 active_procs = system_info.P_ACTIVE;
680 if (active_procs > topn)
684 if (active_procs > max_topn)
686 active_procs = max_topn;
689 /* now show the top "n" processes. */
690 for (i = 0; i < active_procs; i++)
692 (*d_process)(i, format_next_process(processes, get_userid,
701 /* do end-screen processing */
704 /* now, flush the output buffer */
705 if (fflush(stdout) != 0)
707 new_message(MT_standout, " Write error on stdout");
713 /* only do the rest if we have more displays to show */
716 /* switch out for new display on smart terminals */
725 d_loadave = u_loadave;
726 d_procstates = u_procstates;
727 d_cpustates = u_cpustates;
732 d_message = u_message;
734 d_process = u_process;
747 else while (no_command)
749 /* assume valid command unless told otherwise */
752 /* set up arguments for select with timeout */
754 FD_SET(0, &readfds); /* for standard input */
755 timeout.tv_sec = delay;
764 /* move to the lower left */
768 /* default the signal handler action */
769 (void) signal(SIGTSTP, SIG_DFL);
771 /* unblock the signal and send ourselves one */
775 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
777 (void) kill(0, SIGTSTP);
779 /* reset the signal handler */
780 (void) signal(SIGTSTP, tstop);
790 /* reascertain the screen dimensions */
793 /* tell display to resize */
794 max_topn = display_resize();
796 /* reset the signal handler */
797 (void) signal(SIGWINCH, winch);
804 /* wait for either input or the end of the delay period */
805 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
806 if (sel_ret < 0 && errno != EINTR)
813 /* something to read -- clear the message area first */
816 /* now read it and convert to command strchr */
817 /* (use "change" as a temporary to hold strchr) */
818 if (read(0, &ch, 1) != 1)
820 /* read error: either 0 or -1 */
821 new_message(MT_standout, " Read error on stdin");
826 if ((iptr = strchr(command_chars, ch)) == NULL)
828 if (ch != '\r' && ch != '\n')
830 /* illegal command */
831 new_message(MT_standout, " Command not understood");
838 change = iptr - command_chars;
839 if (overstrike && change > CMD_OSLIMIT)
842 new_message(MT_standout,
843 " Command cannot be handled by this terminal");
849 case CMD_redraw: /* redraw screen */
853 case CMD_update: /* merely update display */
854 /* is the load average high? */
855 if (system_info.load_avg[0] > LoadMax)
857 /* yes, go home for visual feedback */
863 case CMD_quit: /* quit */
868 case CMD_help1: /* help */
873 standout("Hit any key to continue: ");
875 (void) read(0, &ch, 1);
878 case CMD_errors: /* show errors */
879 if (error_count() == 0)
881 new_message(MT_standout,
882 " Currently no errors to report.");
891 standout("Hit any key to continue: ");
893 (void) read(0, &ch, 1);
897 case CMD_number1: /* new number */
899 new_message(MT_standout,
900 "Number of processes to show: ");
901 newval = readline(tempbuf1, 8, Yes);
904 if (newval > max_topn)
906 new_message(MT_standout | MT_delayed,
907 " This terminal can only display %d processes.",
914 /* inhibit the header */
917 else if (newval > topn && topn == 0)
919 /* redraw the header */
927 case CMD_delay: /* new seconds delay */
928 new_message(MT_standout, "Seconds to delay: ");
929 if ((i = readline(tempbuf1, 8, Yes)) > -1)
931 if ((delay = i) == 0 && getuid() != 0)
939 case CMD_displays: /* change display count */
940 new_message(MT_standout,
941 "Displays to show (currently %s): ",
942 displays == -1 ? "infinite" :
944 if ((i = readline(tempbuf1, 10, Yes)) > 0)
955 case CMD_kill: /* kill program */
956 new_message(0, "kill ");
957 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
959 if ((errmsg = kill_procs(tempbuf2)) != NULL)
961 new_message(MT_standout, "%s", errmsg);
972 case CMD_renice: /* renice program */
973 new_message(0, "renice ");
974 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
976 if ((errmsg = renice_procs(tempbuf2)) != NULL)
978 new_message(MT_standout, "%s", errmsg);
992 new_message(MT_standout | MT_delayed,
993 " %sisplaying idle processes.",
994 ps.idle ? "D" : "Not d");
999 ps.self = (ps.self == -1) ? getpid() : -1;
1000 new_message(MT_standout | MT_delayed,
1001 " %sisplaying self.",
1002 (ps.self == -1) ? "D" : "Not d");
1007 new_message(MT_standout,
1008 "Username to show (+ for all): ");
1009 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1011 if (tempbuf2[0] == '+' &&
1012 tempbuf2[1] == '\0')
1016 else if ((i = userid(tempbuf2)) == -1)
1018 new_message(MT_standout,
1019 " %s: unknown user", tempbuf2);
1035 ps.thread = !ps.thread;
1036 new_message(MT_standout | MT_delayed,
1037 " Displaying threads %s",
1038 ps.thread ? "separately" : "as a count");
1039 header_text = format_header(uname_field);
1045 new_message(MT_standout | MT_delayed,
1046 " Displaying %s CPU",
1047 ps.wcpu ? "weighted" : "raw");
1048 header_text = format_header(uname_field);
1053 if (++displaymode == DISP_MAX)
1055 header_text = format_header(uname_field);
1056 display_header(Yes);
1057 d_header = i_header;
1061 ps.system = !ps.system;
1064 fmt_flags ^= FMT_SHOWARGS;
1068 new_message(MT_standout,
1070 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1072 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1074 new_message(MT_standout,
1075 " %s: unrecognized sorting order", tempbuf2);
1092 new_message(MT_standout | MT_delayed,
1093 " %sisplaying jail ID.",
1094 ps.jail ? "D" : "Not d");
1095 header_text = format_header(uname_field);
1101 new_message(MT_standout,
1102 "Jail to show (+ for all): ");
1103 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1105 if (tempbuf2[0] == '+' &&
1106 tempbuf2[1] == '\0')
1110 else if ((i = jail_getid(tempbuf2)) == -1)
1112 new_message(MT_standout,
1113 " %s: unknown jail", tempbuf2);
1122 new_message(MT_standout |
1123 MT_delayed, " Displaying jail "
1126 format_header(uname_field);
1138 ps.kidle = !ps.kidle;
1139 new_message(MT_standout | MT_delayed,
1140 " %sisplaying system idle process.",
1141 ps.kidle ? "D" : "Not d");
1145 pcpu_stats = !pcpu_stats;
1146 new_message(MT_standout | MT_delayed,
1147 " Displaying %sCPU statistics.",
1148 pcpu_stats ? "per-" : "global ");
1150 max_topn = display_updatecpus(&statics);
1156 new_message(MT_standout | MT_delayed,
1157 " %sisplaying per-process swap usage.",
1158 ps.swap ? "D" : "Not d");
1159 header_text = format_header(uname_field);
1164 new_message(MT_standout, " BAD CASE IN SWITCH!");
1169 /* flush out stuff that may have been written */
1184 * reset_display() - reset all the display routine pointers so that entire
1185 * screen will get redrawn.
1192 d_loadave = i_loadave;
1193 d_procstates = i_procstates;
1194 d_cpustates = i_cpustates;
1195 d_memory = i_memory;
1199 d_message = i_message;
1200 d_header = i_header;
1201 d_process = i_process;
1208 sigret_t leave() /* exit under normal conditions -- INT handler */
1214 sigret_t tstop(i) /* SIGTSTP handler */
1223 sigret_t winch(i) /* SIGWINCH handler */
1232 void quit(status) /* exit under duress */