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();
117 /* different routines for displaying the user's identification */
118 /* (values assigned to get_userid) */
122 /* pointers to display routines */
123 void (*d_loadave)() = i_loadave;
124 void (*d_procstates)() = i_procstates;
125 void (*d_cpustates)() = i_cpustates;
126 void (*d_memory)() = i_memory;
127 void (*d_arc)() = i_arc;
128 void (*d_swap)() = i_swap;
129 void (*d_message)() = i_message;
130 void (*d_header)() = i_header;
131 void (*d_process)() = i_process;
133 void reset_display(void);
144 register int active_procs;
147 struct system_info system_info;
148 struct statics statics;
151 static char tempbuf1[50];
152 static char tempbuf2[50];
153 int old_sigmask; /* only used for BSD-style signals */
154 int topn = Default_TOPN;
155 int delay = Default_DELAY;
156 int displays = 0; /* indicates unspecified */
159 char *(*get_userid)() = username;
160 char *uname_field = "USERNAME";
168 char do_unames = Yes;
169 char interactive = Maybe;
171 #if Default_TOPN == Infinity
172 char topn_specified = No;
177 struct timeval timeout;
179 char *order_name = NULL;
183 /* FD_SET and friends are not present: fake it */
185 #define FD_ZERO(x) (*(x) = 0)
186 #define FD_SET(f, x) (*(x) = 1<<f)
191 static char command_chars[] = "\f qh?en#sdkriIutHmSCajzPJwo";
193 static char command_chars[] = "\f qh?en#sdkriIutHmSCajzPJw";
195 /* these defines enumerate the "strchr"s of the commands in command_chars */
201 #define CMD_OSLIMIT 4 /* terminals with OS can only handle commands */
202 #define CMD_errors 5 /* less than or equal to CMD_OSLIMIT */
203 #define CMD_number1 6
204 #define CMD_number2 7
206 #define CMD_displays 9
208 #define CMD_renice 11
209 #define CMD_idletog 12
210 #define CMD_idletog2 13
212 #define CMD_selftog 15
213 #define CMD_thrtog 16
214 #define CMD_viewtog 17
215 #define CMD_viewsys 18
216 #define CMD_wcputog 19
217 #define CMD_showargs 20
218 #define CMD_jidtog 21
219 #define CMD_kidletog 22
220 #define CMD_pcputog 23
222 #define CMD_swaptog 25
227 /* set the buffer for stdout */
230 debug = fopen("debug.run", "w");
231 setbuffer(stdout, NULL, 0);
233 setbuffer(stdout, stdoutbuf, Buffersize);
239 if ((myname = strrchr(argv[0], '/')) == 0)
249 /* initialize some selection options */
262 /* get preset options from the environment */
263 if ((env_top = getenv("TOP")) != NULL)
265 av = preset_argv = argparse(env_top, &preset_argc);
268 /* set the dummy argument to an explanatory message, in case
269 getopt encounters a bad argument */
270 preset_argv[0] = "while processing environment";
273 /* process options */
275 /* if we're done doing the presets, then process the real arguments */
276 if (preset_argc == 0)
281 /* this should keep getopt happy... */
285 while ((i = getopt(ac, av, "CSIHPabijJ:nquvzs:d:U:m:o:tw")) != EOF)
289 case 'v': /* show version number */
290 fprintf(stderr, "%s: version %s\n",
291 myname, version_string());
295 case 'u': /* toggle uid/username display */
296 do_unames = !do_unames;
299 case 'U': /* display only username's processes */
300 if ((ps.uid = userid(optarg)) == -1)
302 fprintf(stderr, "%s: unknown user\n", optarg);
307 case 'S': /* show system processes */
308 ps.system = !ps.system;
311 case 'I': /* show idle processes */
315 case 'i': /* go interactive regardless */
319 case 'n': /* batch, or non-interactive */
325 fmt_flags ^= FMT_SHOWARGS;
328 case 'd': /* number of displays to show */
329 if ((i = atoiwi(optarg)) == Invalid || i == 0)
332 "%s: warning: display count should be positive -- option ignored\n",
343 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
346 "%s: warning: seconds delay should be positive -- using default\n",
348 delay = Default_DELAY;
353 case 'q': /* be quick about it */
354 /* only allow this if user is really root */
357 /* be very un-nice! */
363 "%s: warning: `-q' option can only be used by root\n",
369 case 'm': /* select display mode */
370 if (strcmp(optarg, "io") == 0) {
371 displaymode = DISP_IO;
372 } else if (strcmp(optarg, "cpu") == 0) {
373 displaymode = DISP_CPU;
376 "%s: warning: `-m' option can only take args "
383 case 'o': /* select sort order */
388 "%s: this platform does not support arbitrary ordering. Sorry.\n",
395 ps.self = (ps.self == -1) ? getpid() : -1;
403 ps.thread = !ps.thread;
410 case 'J': /* display only jail's processes */
411 if ((ps.jid = jail_getid(optarg)) == -1)
413 fprintf(stderr, "%s: unknown jail\n", optarg);
420 pcpu_stats = !pcpu_stats;
428 ps.kidle = !ps.kidle;
434 "Usage: %s [-abCHIijnPqStuvz] [-d count] [-m io | cpu] [-o field] [-s time]\n"
435 " [-J jail] [-U username] [number]\n",
436 version_string(), myname);
441 /* get count of top processes to display (if any) */
444 if ((topn = atoiwi(av[optind])) == Invalid)
447 "%s: warning: process display count should be non-negative -- using default\n",
451 #if Default_TOPN == Infinity
454 topn_specified = Yes;
459 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
463 /* repeat only if we really did the preset arguments */
466 /* set constants for username/uid display correctly */
469 uname_field = " UID ";
473 /* initialize the kernel memory interface */
474 if (machine_init(&statics, do_unames) == -1)
480 /* determine sorting order index, if necessary */
481 if (order_name != NULL)
483 if ((order_index = string_index(order_name, statics.order_names)) == -1)
487 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
489 fprintf(stderr, "\tTry one of these:");
490 pp = statics.order_names;
493 fprintf(stderr, " %s", *pp++);
501 #ifdef no_initialization_needed
502 /* initialize the hashing stuff */
509 /* initialize termcap */
510 init_termcap(interactive);
512 /* get the string to use for the process area header */
513 header_text = format_header(uname_field);
515 /* initialize display interface */
516 if ((max_topn = display_init(&statics)) == -1)
518 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
522 /* print warning if user requested more processes than we can display */
526 "%s: warning: this terminal can only display %d processes.\n",
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 #if Default_TOPN == Infinity
545 topn = smart_terminal ? Largest :
546 (topn_specified ? Largest : Nominal_TOPN);
552 /* set header display accordingly */
553 display_header(topn > 0);
555 /* determine interactive state */
556 if (interactive == Maybe)
558 interactive = smart_terminal;
561 /* if # of displays not specified, fill it in */
564 displays = smart_terminal ? Infinity : 1;
567 /* hold interrupt signals while setting up the screen and the handlers */
573 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
576 (void) signal(SIGINT, leave);
577 (void) signal(SIGQUIT, leave);
578 (void) signal(SIGTSTP, tstop);
580 (void) signal(SIGWINCH, winch);
587 (void) sigsetmask(old_sigmask);
591 fputs("....", stderr);
592 fflush(stderr); /* why must I do this? */
593 sleep((unsigned)(3 * warnings));
600 * main loop -- repeat while display count is positive or while it
601 * indicates infinity (by being -1)
604 while ((displays == -1) || (displays-- > 0))
609 /* get the current stats */
610 get_system_info(&system_info);
613 compare = compares[order_index];
615 if (displaymode == DISP_CPU)
616 compare = proc_compare;
618 compare = io_compare;
621 /* get the current set of processes */
623 get_process_info(&system_info, &ps, compare);
625 /* display the load averages */
626 (*d_loadave)(system_info.last_pid,
627 system_info.load_avg);
629 /* display the current time */
630 /* this method of getting the time SHOULD be fairly portable */
632 i_uptime(&system_info.boottime, &curr_time);
633 i_timeofday(&curr_time);
635 /* display process state breakdown */
636 (*d_procstates)(system_info.p_total,
637 system_info.procstates);
639 /* display the cpu state percentage breakdown */
640 if (dostates) /* but not the first time */
642 (*d_cpustates)(system_info.cpustates);
646 /* we'll do it next time */
658 /* display memory stats */
659 (*d_memory)(system_info.memory);
660 (*d_arc)(system_info.arc);
662 /* display swap stats */
663 (*d_swap)(system_info.swap);
665 /* handle message area */
668 /* update the header area */
669 (*d_header)(header_text);
673 /* determine number of processes to actually display */
674 /* this number will be the smallest of: active processes,
675 number user requested, number current screen accomodates */
676 active_procs = system_info.P_ACTIVE;
677 if (active_procs > topn)
681 if (active_procs > max_topn)
683 active_procs = max_topn;
686 /* now show the top "n" processes. */
687 for (i = 0; i < active_procs; i++)
689 (*d_process)(i, format_next_process(processes, get_userid,
698 /* do end-screen processing */
701 /* now, flush the output buffer */
702 if (fflush(stdout) != 0)
704 new_message(MT_standout, " Write error on stdout");
710 /* only do the rest if we have more displays to show */
713 /* switch out for new display on smart terminals */
722 d_loadave = u_loadave;
723 d_procstates = u_procstates;
724 d_cpustates = u_cpustates;
728 d_message = u_message;
730 d_process = u_process;
743 else while (no_command)
745 /* assume valid command unless told otherwise */
748 /* set up arguments for select with timeout */
750 FD_SET(0, &readfds); /* for standard input */
751 timeout.tv_sec = delay;
760 /* move to the lower left */
764 /* default the signal handler action */
765 (void) signal(SIGTSTP, SIG_DFL);
767 /* unblock the signal and send ourselves one */
771 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
773 (void) kill(0, SIGTSTP);
775 /* reset the signal handler */
776 (void) signal(SIGTSTP, tstop);
786 /* reascertain the screen dimensions */
789 /* tell display to resize */
790 max_topn = display_resize();
792 /* reset the signal handler */
793 (void) signal(SIGWINCH, winch);
800 /* wait for either input or the end of the delay period */
801 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
802 if (sel_ret < 0 && errno != EINTR)
809 /* something to read -- clear the message area first */
812 /* now read it and convert to command strchr */
813 /* (use "change" as a temporary to hold strchr) */
814 if (read(0, &ch, 1) != 1)
816 /* read error: either 0 or -1 */
817 new_message(MT_standout, " Read error on stdin");
822 if ((iptr = strchr(command_chars, ch)) == NULL)
824 if (ch != '\r' && ch != '\n')
826 /* illegal command */
827 new_message(MT_standout, " Command not understood");
834 change = iptr - command_chars;
835 if (overstrike && change > CMD_OSLIMIT)
838 new_message(MT_standout,
839 " Command cannot be handled by this terminal");
845 case CMD_redraw: /* redraw screen */
849 case CMD_update: /* merely update display */
850 /* is the load average high? */
851 if (system_info.load_avg[0] > LoadMax)
853 /* yes, go home for visual feedback */
859 case CMD_quit: /* quit */
864 case CMD_help1: /* help */
869 standout("Hit any key to continue: ");
871 (void) read(0, &ch, 1);
874 case CMD_errors: /* show errors */
875 if (error_count() == 0)
877 new_message(MT_standout,
878 " Currently no errors to report.");
887 standout("Hit any key to continue: ");
889 (void) read(0, &ch, 1);
893 case CMD_number1: /* new number */
895 new_message(MT_standout,
896 "Number of processes to show: ");
897 newval = readline(tempbuf1, 8, Yes);
900 if (newval > max_topn)
902 new_message(MT_standout | MT_delayed,
903 " This terminal can only display %d processes.",
910 /* inhibit the header */
913 else if (newval > topn && topn == 0)
915 /* redraw the header */
923 case CMD_delay: /* new seconds delay */
924 new_message(MT_standout, "Seconds to delay: ");
925 if ((i = readline(tempbuf1, 8, Yes)) > -1)
927 if ((delay = i) == 0 && getuid() != 0)
935 case CMD_displays: /* change display count */
936 new_message(MT_standout,
937 "Displays to show (currently %s): ",
938 displays == -1 ? "infinite" :
940 if ((i = readline(tempbuf1, 10, Yes)) > 0)
951 case CMD_kill: /* kill program */
952 new_message(0, "kill ");
953 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
955 if ((errmsg = kill_procs(tempbuf2)) != NULL)
957 new_message(MT_standout, "%s", errmsg);
968 case CMD_renice: /* renice program */
969 new_message(0, "renice ");
970 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
972 if ((errmsg = renice_procs(tempbuf2)) != NULL)
974 new_message(MT_standout, "%s", errmsg);
988 new_message(MT_standout | MT_delayed,
989 " %sisplaying idle processes.",
990 ps.idle ? "D" : "Not d");
995 ps.self = (ps.self == -1) ? getpid() : -1;
996 new_message(MT_standout | MT_delayed,
997 " %sisplaying self.",
998 (ps.self == -1) ? "D" : "Not d");
1003 new_message(MT_standout,
1004 "Username to show (+ for all): ");
1005 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1007 if (tempbuf2[0] == '+' &&
1008 tempbuf2[1] == '\0')
1012 else if ((i = userid(tempbuf2)) == -1)
1014 new_message(MT_standout,
1015 " %s: unknown user", tempbuf2);
1031 ps.thread = !ps.thread;
1032 new_message(MT_standout | MT_delayed,
1033 " Displaying threads %s",
1034 ps.thread ? "separately" : "as a count");
1035 header_text = format_header(uname_field);
1041 new_message(MT_standout | MT_delayed,
1042 " Displaying %s CPU",
1043 ps.wcpu ? "weighted" : "raw");
1044 header_text = format_header(uname_field);
1049 if (++displaymode == DISP_MAX)
1051 header_text = format_header(uname_field);
1052 display_header(Yes);
1053 d_header = i_header;
1057 ps.system = !ps.system;
1060 fmt_flags ^= FMT_SHOWARGS;
1064 new_message(MT_standout,
1066 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1068 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1070 new_message(MT_standout,
1071 " %s: unrecognized sorting order", tempbuf2);
1088 new_message(MT_standout | MT_delayed,
1089 " %sisplaying jail ID.",
1090 ps.jail ? "D" : "Not d");
1091 header_text = format_header(uname_field);
1097 new_message(MT_standout,
1098 "Jail to show (+ for all): ");
1099 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1101 if (tempbuf2[0] == '+' &&
1102 tempbuf2[1] == '\0')
1106 else if ((i = jail_getid(tempbuf2)) == -1)
1108 new_message(MT_standout,
1109 " %s: unknown jail", tempbuf2);
1118 new_message(MT_standout |
1119 MT_delayed, " Displaying jail "
1122 format_header(uname_field);
1134 ps.kidle = !ps.kidle;
1135 new_message(MT_standout | MT_delayed,
1136 " %sisplaying system idle process.",
1137 ps.kidle ? "D" : "Not d");
1141 pcpu_stats = !pcpu_stats;
1142 new_message(MT_standout | MT_delayed,
1143 " Displaying %sCPU statistics.",
1144 pcpu_stats ? "per-" : "global ");
1146 max_topn = display_updatecpus(&statics);
1152 new_message(MT_standout | MT_delayed,
1153 " %sisplaying per-process swap usage.",
1154 ps.swap ? "D" : "Not d");
1155 header_text = format_header(uname_field);
1160 new_message(MT_standout, " BAD CASE IN SWITCH!");
1165 /* flush out stuff that may have been written */
1180 * reset_display() - reset all the display routine pointers so that entire
1181 * screen will get redrawn.
1188 d_loadave = i_loadave;
1189 d_procstates = i_procstates;
1190 d_cpustates = i_cpustates;
1191 d_memory = i_memory;
1194 d_message = i_message;
1195 d_header = i_header;
1196 d_process = i_process;
1203 sigret_t leave() /* exit under normal conditions -- INT handler */
1209 sigret_t tstop(i) /* SIGTSTP handler */
1218 sigret_t winch(i) /* SIGWINCH handler */
1227 void quit(status) /* exit under duress */