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
49 /* includes specific to top */
51 #include "display.h" /* interface to display package */
52 #include "screen.h" /* interface to screen package */
54 #include "top.local.h"
60 /* Size of the stdio buffer given to stdout */
61 #define Buffersize 2048
63 /* The buffer that stdio will use */
64 char stdoutbuf[Buffersize];
66 /* build Signal masks */
67 #define Smask(s) (1 << ((s) - 1))
73 /* imported from screen.c */
74 extern int overstrike;
76 static int fmt_flags = 0;
79 /* signal handling routines */
83 sigret_t top_winch(int);
86 volatile sig_atomic_t leaveflag;
87 volatile sig_atomic_t tstopflag;
88 volatile sig_atomic_t winchflag;
90 /* internal routines */
93 /* values which need to be accessed by signal handlers */
94 static int max_topn; /* maximum displayable processes */
96 /* miscellaneous things */
97 struct process_select ps;
101 /* routines that don't return int */
106 char *renice_procs();
109 extern int (*compares[])();
111 extern int proc_compare();
112 extern int io_compare();
116 caddr_t get_process_info();
118 /* different routines for displaying the user's identification */
119 /* (values assigned to get_userid) */
123 /* pointers to display routines */
124 void (*d_loadave)() = i_loadave;
125 void (*d_procstates)() = i_procstates;
126 void (*d_cpustates)() = i_cpustates;
127 void (*d_memory)() = i_memory;
128 void (*d_arc)() = i_arc;
129 void (*d_carc)() = i_carc;
130 void (*d_swap)() = i_swap;
131 void (*d_message)() = i_message;
132 void (*d_header)() = i_header;
133 void (*d_process)() = i_process;
135 void reset_display(void);
140 for (size_t i = 0; i < TOP_MAX_UIDS; ++i)
149 /* Add the uid if there's room */
150 for (; i < TOP_MAX_UIDS; ++i)
152 if (ps.uid[i] == -1 || ps.uid[i] == uid)
159 return (i == TOP_MAX_UIDS);
166 size_t where = TOP_MAX_UIDS;
168 /* Look for the user to remove - no problem if it's not there */
169 for (; i < TOP_MAX_UIDS; ++i)
173 if (ps.uid[i] == uid)
177 /* Make sure we don't leave a hole in the middle */
178 if (where != TOP_MAX_UIDS)
180 ps.uid[where] = ps.uid[i-1];
186 handle_user(char *buf, size_t buflen)
192 new_message(MT_standout, "Username to show (+ for all): ");
193 if (readline(buf, buflen, No) <= 0)
199 if (buf[0] == '+' || buf[0] == '-')
210 if ((uid = userid(buf2)) == -1)
212 new_message(MT_standout, " %s: unknown user", buf2);
228 new_message(MT_standout, " too many users, reset with '+'");
249 register int active_procs;
252 struct system_info system_info;
253 struct statics statics;
256 static char tempbuf1[50];
257 static char tempbuf2[50];
258 int old_sigmask; /* only used for BSD-style signals */
259 int topn = Default_TOPN;
260 int delay = Default_DELAY;
261 int displays = 0; /* indicates unspecified */
264 char *(*get_userid)() = username;
265 char *uname_field = "USERNAME";
273 char do_unames = Yes;
274 char interactive = Maybe;
276 #if Default_TOPN == Infinity
277 char topn_specified = No;
282 struct timeval timeout;
284 char *order_name = NULL;
288 /* FD_SET and friends are not present: fake it */
290 #define FD_ZERO(x) (*(x) = 0)
291 #define FD_SET(f, x) (*(x) = 1<<f)
296 static char command_chars[] = "\f qh?en#sdkriIutHmSCajzPJwo";
298 static char command_chars[] = "\f qh?en#sdkriIutHmSCajzPJw";
300 /* these defines enumerate the "strchr"s of the commands in command_chars */
306 #define CMD_OSLIMIT 4 /* terminals with OS can only handle commands */
307 #define CMD_errors 5 /* less than or equal to CMD_OSLIMIT */
308 #define CMD_number1 6
309 #define CMD_number2 7
311 #define CMD_displays 9
313 #define CMD_renice 11
314 #define CMD_idletog 12
315 #define CMD_idletog2 13
317 #define CMD_selftog 15
318 #define CMD_thrtog 16
319 #define CMD_viewtog 17
320 #define CMD_viewsys 18
321 #define CMD_wcputog 19
322 #define CMD_showargs 20
323 #define CMD_jidtog 21
324 #define CMD_kidletog 22
325 #define CMD_pcputog 23
327 #define CMD_swaptog 25
332 /* set the buffer for stdout */
335 debug = fopen("debug.run", "w");
336 setbuffer(stdout, NULL, 0);
338 setbuffer(stdout, stdoutbuf, Buffersize);
344 if ((myname = strrchr(argv[0], '/')) == 0)
354 /* initialize some selection options */
367 /* get preset options from the environment */
368 if ((env_top = getenv("TOP")) != NULL)
370 av = preset_argv = argparse(env_top, &preset_argc);
373 /* set the dummy argument to an explanatory message, in case
374 getopt encounters a bad argument */
375 preset_argv[0] = "while processing environment";
378 /* process options */
380 /* if we're done doing the presets, then process the real arguments */
381 if (preset_argc == 0)
386 /* this should keep getopt happy... */
390 while ((i = getopt(ac, av, "CSIHPabijJ:nquvzs:d:U:m:o:tw")) != EOF)
394 case 'v': /* show version number */
395 fprintf(stderr, "%s: version %s\n",
396 myname, version_string());
400 case 'u': /* toggle uid/username display */
401 do_unames = !do_unames;
404 case 'U': /* display only username's processes */
405 if ((ps.uid[0] = userid(optarg)) == -1)
407 fprintf(stderr, "%s: unknown user\n", optarg);
412 case 'S': /* show system processes */
413 ps.system = !ps.system;
416 case 'I': /* show idle processes */
420 case 'i': /* go interactive regardless */
424 case 'n': /* batch, or non-interactive */
430 fmt_flags ^= FMT_SHOWARGS;
433 case 'd': /* number of displays to show */
434 if ((i = atoiwi(optarg)) == Invalid || i == 0)
437 "%s: warning: display count should be positive -- option ignored\n",
448 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
451 "%s: warning: seconds delay should be positive -- using default\n",
453 delay = Default_DELAY;
458 case 'q': /* be quick about it */
459 /* only allow this if user is really root */
462 /* be very un-nice! */
468 "%s: warning: `-q' option can only be used by root\n",
474 case 'm': /* select display mode */
475 if (strcmp(optarg, "io") == 0) {
476 displaymode = DISP_IO;
477 } else if (strcmp(optarg, "cpu") == 0) {
478 displaymode = DISP_CPU;
481 "%s: warning: `-m' option can only take args "
488 case 'o': /* select sort order */
493 "%s: this platform does not support arbitrary ordering. Sorry.\n",
500 ps.self = (ps.self == -1) ? getpid() : -1;
508 ps.thread = !ps.thread;
515 case 'J': /* display only jail's processes */
516 if ((ps.jid = jail_getid(optarg)) == -1)
518 fprintf(stderr, "%s: unknown jail\n", optarg);
525 pcpu_stats = !pcpu_stats;
533 ps.kidle = !ps.kidle;
539 "Usage: %s [-abCHIijnPqStuvwz] [-d count] [-m io | cpu] [-o field] [-s time]\n"
540 " [-J jail] [-U username] [number]\n",
541 version_string(), myname);
546 /* get count of top processes to display (if any) */
549 if ((topn = atoiwi(av[optind])) == Invalid)
552 "%s: warning: process display count should be non-negative -- using default\n",
556 #if Default_TOPN == Infinity
559 topn_specified = Yes;
564 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
568 /* repeat only if we really did the preset arguments */
571 /* set constants for username/uid display correctly */
574 uname_field = " UID ";
578 /* initialize the kernel memory interface */
579 if (machine_init(&statics, do_unames) == -1)
585 /* determine sorting order index, if necessary */
586 if (order_name != NULL)
588 if ((order_index = string_index(order_name, statics.order_names)) == -1)
592 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
594 fprintf(stderr, "\tTry one of these:");
595 pp = statics.order_names;
598 fprintf(stderr, " %s", *pp++);
606 #ifdef no_initialization_needed
607 /* initialize the hashing stuff */
614 /* initialize termcap */
615 init_termcap(interactive);
617 /* get the string to use for the process area header */
618 header_text = format_header(uname_field);
620 /* initialize display interface */
621 if ((max_topn = display_init(&statics)) == -1)
623 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
627 /* print warning if user requested more processes than we can display */
631 "%s: warning: this terminal can only display %d processes.\n",
636 /* adjust for topn == Infinity */
637 if (topn == Infinity)
640 * For smart terminals, infinity really means everything that can
641 * be displayed, or Largest.
642 * On dumb terminals, infinity means every process in the system!
643 * We only really want to do that if it was explicitly specified.
644 * This is always the case when "Default_TOPN != Infinity". But if
645 * topn wasn't explicitly specified and we are on a dumb terminal
646 * and the default is Infinity, then (and only then) we use
647 * "Nominal_TOPN" instead.
649 #if Default_TOPN == Infinity
650 topn = smart_terminal ? Largest :
651 (topn_specified ? Largest : Nominal_TOPN);
657 /* set header display accordingly */
658 display_header(topn > 0);
660 /* determine interactive state */
661 if (interactive == Maybe)
663 interactive = smart_terminal;
666 /* if # of displays not specified, fill it in */
669 displays = smart_terminal ? Infinity : 1;
672 /* hold interrupt signals while setting up the screen and the handlers */
678 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
681 (void) signal(SIGINT, leave);
682 (void) signal(SIGQUIT, leave);
683 (void) signal(SIGTSTP, tstop);
685 (void) signal(SIGWINCH, top_winch);
692 (void) sigsetmask(old_sigmask);
696 fputs("....", stderr);
697 fflush(stderr); /* why must I do this? */
698 sleep((unsigned)(3 * warnings));
705 * main loop -- repeat while display count is positive or while it
706 * indicates infinity (by being -1)
709 while ((displays == -1) || (displays-- > 0))
714 /* get the current stats */
715 get_system_info(&system_info);
718 compare = compares[order_index];
720 if (displaymode == DISP_CPU)
721 compare = proc_compare;
723 compare = io_compare;
726 /* get the current set of processes */
728 get_process_info(&system_info, &ps, compare);
730 /* display the load averages */
731 (*d_loadave)(system_info.last_pid,
732 system_info.load_avg);
734 /* display the current time */
735 /* this method of getting the time SHOULD be fairly portable */
737 i_uptime(&system_info.boottime, &curr_time);
738 i_timeofday(&curr_time);
740 /* display process state breakdown */
741 (*d_procstates)(system_info.p_total,
742 system_info.procstates);
744 /* display the cpu state percentage breakdown */
745 if (dostates) /* but not the first time */
747 (*d_cpustates)(system_info.cpustates);
751 /* we'll do it next time */
763 /* display memory stats */
764 (*d_memory)(system_info.memory);
765 (*d_arc)(system_info.arc);
766 (*d_carc)(system_info.carc);
768 /* display swap stats */
769 (*d_swap)(system_info.swap);
771 /* handle message area */
774 /* update the header area */
775 (*d_header)(header_text);
779 /* determine number of processes to actually display */
780 /* this number will be the smallest of: active processes,
781 number user requested, number current screen accomodates */
782 active_procs = system_info.P_ACTIVE;
783 if (active_procs > topn)
787 if (active_procs > max_topn)
789 active_procs = max_topn;
792 /* now show the top "n" processes. */
793 for (i = 0; i < active_procs; i++)
795 (*d_process)(i, format_next_process(processes, get_userid,
804 /* do end-screen processing */
807 /* now, flush the output buffer */
808 if (fflush(stdout) != 0)
810 new_message(MT_standout, " Write error on stdout");
816 /* only do the rest if we have more displays to show */
819 /* switch out for new display on smart terminals */
828 d_loadave = u_loadave;
829 d_procstates = u_procstates;
830 d_cpustates = u_cpustates;
835 d_message = u_message;
837 d_process = u_process;
850 else while (no_command)
852 /* assume valid command unless told otherwise */
855 /* set up arguments for select with timeout */
857 FD_SET(0, &readfds); /* for standard input */
858 timeout.tv_sec = delay;
867 /* move to the lower left */
871 /* default the signal handler action */
872 (void) signal(SIGTSTP, SIG_DFL);
874 /* unblock the signal and send ourselves one */
878 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
880 (void) kill(0, SIGTSTP);
882 /* reset the signal handler */
883 (void) signal(SIGTSTP, tstop);
893 /* reascertain the screen dimensions */
896 /* tell display to resize */
897 max_topn = display_resize();
899 /* reset the signal handler */
900 (void) signal(SIGWINCH, top_winch);
907 /* wait for either input or the end of the delay period */
908 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
909 if (sel_ret < 0 && errno != EINTR)
916 /* something to read -- clear the message area first */
919 /* now read it and convert to command strchr */
920 /* (use "change" as a temporary to hold strchr) */
921 if (read(0, &ch, 1) != 1)
923 /* read error: either 0 or -1 */
924 new_message(MT_standout, " Read error on stdin");
929 if ((iptr = strchr(command_chars, ch)) == NULL)
931 if (ch != '\r' && ch != '\n')
933 /* illegal command */
934 new_message(MT_standout, " Command not understood");
941 change = iptr - command_chars;
942 if (overstrike && change > CMD_OSLIMIT)
945 new_message(MT_standout,
946 " Command cannot be handled by this terminal");
952 case CMD_redraw: /* redraw screen */
956 case CMD_update: /* merely update display */
957 /* is the load average high? */
958 if (system_info.load_avg[0] > LoadMax)
960 /* yes, go home for visual feedback */
966 case CMD_quit: /* quit */
971 case CMD_help1: /* help */
976 top_standout("Hit any key to continue: ");
978 (void) read(0, &ch, 1);
981 case CMD_errors: /* show errors */
982 if (error_count() == 0)
984 new_message(MT_standout,
985 " Currently no errors to report.");
994 top_standout("Hit any key to continue: ");
996 (void) read(0, &ch, 1);
1000 case CMD_number1: /* new number */
1002 new_message(MT_standout,
1003 "Number of processes to show: ");
1004 newval = readline(tempbuf1, 8, Yes);
1007 if (newval > max_topn)
1009 new_message(MT_standout | MT_delayed,
1010 " This terminal can only display %d processes.",
1017 /* inhibit the header */
1020 else if (newval > topn && topn == 0)
1022 /* redraw the header */
1023 display_header(Yes);
1024 d_header = i_header;
1030 case CMD_delay: /* new seconds delay */
1031 new_message(MT_standout, "Seconds to delay: ");
1032 if ((i = readline(tempbuf1, 8, Yes)) > -1)
1034 if ((delay = i) == 0 && getuid() != 0)
1042 case CMD_displays: /* change display count */
1043 new_message(MT_standout,
1044 "Displays to show (currently %s): ",
1045 displays == -1 ? "infinite" :
1047 if ((i = readline(tempbuf1, 10, Yes)) > 0)
1058 case CMD_kill: /* kill program */
1059 new_message(0, "kill ");
1060 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1062 if ((errmsg = kill_procs(tempbuf2)) != NULL)
1064 new_message(MT_standout, "%s", errmsg);
1075 case CMD_renice: /* renice program */
1076 new_message(0, "renice ");
1077 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1079 if ((errmsg = renice_procs(tempbuf2)) != NULL)
1081 new_message(MT_standout, "%s", errmsg);
1095 new_message(MT_standout | MT_delayed,
1096 " %sisplaying idle processes.",
1097 ps.idle ? "D" : "Not d");
1102 ps.self = (ps.self == -1) ? getpid() : -1;
1103 new_message(MT_standout | MT_delayed,
1104 " %sisplaying self.",
1105 (ps.self == -1) ? "D" : "Not d");
1110 if (handle_user(tempbuf2, sizeof(tempbuf2)))
1115 ps.thread = !ps.thread;
1116 new_message(MT_standout | MT_delayed,
1117 " Displaying threads %s",
1118 ps.thread ? "separately" : "as a count");
1119 header_text = format_header(uname_field);
1125 new_message(MT_standout | MT_delayed,
1126 " Displaying %s CPU",
1127 ps.wcpu ? "weighted" : "raw");
1128 header_text = format_header(uname_field);
1133 if (++displaymode == DISP_MAX)
1135 header_text = format_header(uname_field);
1136 display_header(Yes);
1137 d_header = i_header;
1141 ps.system = !ps.system;
1144 fmt_flags ^= FMT_SHOWARGS;
1148 new_message(MT_standout,
1150 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1152 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1154 new_message(MT_standout,
1155 " %s: unrecognized sorting order", tempbuf2);
1172 new_message(MT_standout | MT_delayed,
1173 " %sisplaying jail ID.",
1174 ps.jail ? "D" : "Not d");
1175 header_text = format_header(uname_field);
1181 new_message(MT_standout,
1182 "Jail to show (+ for all): ");
1183 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1185 if (tempbuf2[0] == '+' &&
1186 tempbuf2[1] == '\0')
1190 else if ((i = jail_getid(tempbuf2)) == -1)
1192 new_message(MT_standout,
1193 " %s: unknown jail", tempbuf2);
1202 new_message(MT_standout |
1203 MT_delayed, " Displaying jail "
1206 format_header(uname_field);
1218 ps.kidle = !ps.kidle;
1219 new_message(MT_standout | MT_delayed,
1220 " %sisplaying system idle process.",
1221 ps.kidle ? "D" : "Not d");
1225 pcpu_stats = !pcpu_stats;
1226 new_message(MT_standout | MT_delayed,
1227 " Displaying %sCPU statistics.",
1228 pcpu_stats ? "per-" : "global ");
1230 max_topn = display_updatecpus(&statics);
1236 new_message(MT_standout | MT_delayed,
1237 " %sisplaying per-process swap usage.",
1238 ps.swap ? "D" : "Not d");
1239 header_text = format_header(uname_field);
1244 new_message(MT_standout, " BAD CASE IN SWITCH!");
1249 /* flush out stuff that may have been written */
1264 * reset_display() - reset all the display routine pointers so that entire
1265 * screen will get redrawn.
1272 d_loadave = i_loadave;
1273 d_procstates = i_procstates;
1274 d_cpustates = i_cpustates;
1275 d_memory = i_memory;
1279 d_message = i_message;
1280 d_header = i_header;
1281 d_process = i_process;
1288 sigret_t leave() /* exit under normal conditions -- INT handler */
1294 sigret_t tstop(i) /* SIGTSTP handler */
1303 sigret_t top_winch(int i) /* SIGWINCH handler */
1309 void quit(status) /* exit under duress */