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
45 /* includes specific to top */
46 #include "display.h" /* interface to display package */
47 #include "screen.h" /* interface to screen package */
49 #include "top.local.h"
54 /* Size of the stdio buffer given to stdout */
55 #define Buffersize 2048
57 /* The buffer that stdio will use */
58 char stdoutbuf[Buffersize];
60 /* build Signal masks */
61 #define Smask(s) (1 << ((s) - 1))
67 /* imported from screen.c */
68 extern int overstrike;
70 static int fmt_flags = 0;
73 /* signal handling routines */
80 volatile sig_atomic_t leaveflag;
81 volatile sig_atomic_t tstopflag;
82 volatile sig_atomic_t winchflag;
84 /* internal routines */
87 /* values which need to be accessed by signal handlers */
88 static int max_topn; /* maximum displayable processes */
90 /* miscellaneous things */
91 struct process_select ps;
95 /* routines that don't return int */
100 char *renice_procs();
103 extern int (*compares[])();
105 extern int proc_compare();
106 extern int io_compare();
110 caddr_t get_process_info();
112 /* different routines for displaying the user's identification */
113 /* (values assigned to get_userid) */
117 /* display routines that need to be predeclared */
137 /* pointers to display routines */
138 int (*d_loadave)() = i_loadave;
139 int (*d_procstates)() = i_procstates;
140 int (*d_cpustates)() = i_cpustates;
141 int (*d_memory)() = i_memory;
142 int (*d_arc)() = i_arc;
143 int (*d_swap)() = i_swap;
144 int (*d_message)() = i_message;
145 int (*d_header)() = i_header;
146 int (*d_process)() = i_process;
156 register int active_procs;
159 struct system_info system_info;
160 struct statics statics;
163 static char tempbuf1[50];
164 static char tempbuf2[50];
165 int old_sigmask; /* only used for BSD-style signals */
166 int topn = Default_TOPN;
167 int delay = Default_DELAY;
168 int displays = 0; /* indicates unspecified */
171 char *(*get_userid)() = username;
172 char *uname_field = "USERNAME";
180 char do_unames = Yes;
181 char interactive = Maybe;
183 #if Default_TOPN == Infinity
184 char topn_specified = No;
189 struct timeval timeout;
191 char *order_name = NULL;
195 /* FD_SET and friends are not present: fake it */
197 #define FD_ZERO(x) (*(x) = 0)
198 #define FD_SET(f, x) (*(x) = 1<<f)
203 static char command_chars[] = "\f qh?en#sdkriIutHmSCajzPJo";
205 static char command_chars[] = "\f qh?en#sdkriIutHmSCajzPJ";
207 /* these defines enumerate the "strchr"s of the commands in command_chars */
213 #define CMD_OSLIMIT 4 /* terminals with OS can only handle commands */
214 #define CMD_errors 5 /* less than or equal to CMD_OSLIMIT */
215 #define CMD_number1 6
216 #define CMD_number2 7
218 #define CMD_displays 9
220 #define CMD_renice 11
221 #define CMD_idletog 12
222 #define CMD_idletog2 13
224 #define CMD_selftog 15
225 #define CMD_thrtog 16
226 #define CMD_viewtog 17
227 #define CMD_viewsys 18
228 #define CMD_wcputog 19
229 #define CMD_showargs 20
230 #define CMD_jidtog 21
231 #define CMD_kidletog 22
232 #define CMD_pcputog 23
238 /* set the buffer for stdout */
241 debug = fopen("debug.run", "w");
242 setbuffer(stdout, NULL, 0);
244 setbuffer(stdout, stdoutbuf, Buffersize);
250 if ((myname = strrchr(argv[0], '/')) == 0)
260 /* initialize some selection options */
272 /* get preset options from the environment */
273 if ((env_top = getenv("TOP")) != NULL)
275 av = preset_argv = argparse(env_top, &preset_argc);
278 /* set the dummy argument to an explanatory message, in case
279 getopt encounters a bad argument */
280 preset_argv[0] = "while processing environment";
283 /* process options */
285 /* if we're done doing the presets, then process the real arguments */
286 if (preset_argc == 0)
291 /* this should keep getopt happy... */
295 while ((i = getopt(ac, av, "CSIHPabijJ:nquvzs:d:U:m:o:t")) != EOF)
299 case 'v': /* show version number */
300 fprintf(stderr, "%s: version %s\n",
301 myname, version_string());
305 case 'u': /* toggle uid/username display */
306 do_unames = !do_unames;
309 case 'U': /* display only username's processes */
310 if ((ps.uid = userid(optarg)) == -1)
312 fprintf(stderr, "%s: unknown user\n", optarg);
317 case 'S': /* show system processes */
318 ps.system = !ps.system;
321 case 'I': /* show idle processes */
325 case 'i': /* go interactive regardless */
329 case 'n': /* batch, or non-interactive */
335 fmt_flags ^= FMT_SHOWARGS;
338 case 'd': /* number of displays to show */
339 if ((i = atoiwi(optarg)) == Invalid || i == 0)
342 "%s: warning: display count should be positive -- option ignored\n",
353 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
356 "%s: warning: seconds delay should be positive -- using default\n",
358 delay = Default_DELAY;
363 case 'q': /* be quick about it */
364 /* only allow this if user is really root */
367 /* be very un-nice! */
373 "%s: warning: `-q' option can only be used by root\n",
379 case 'm': /* select display mode */
380 if (strcmp(optarg, "io") == 0) {
381 displaymode = DISP_IO;
382 } else if (strcmp(optarg, "cpu") == 0) {
383 displaymode = DISP_CPU;
386 "%s: warning: `-m' option can only take args "
393 case 'o': /* select sort order */
398 "%s: this platform does not support arbitrary ordering. Sorry.\n",
405 ps.self = (ps.self == -1) ? getpid() : -1;
413 ps.thread = !ps.thread;
420 case 'J': /* display only jail's processes */
421 if ((ps.jid = jail_getid(optarg)) == -1)
423 fprintf(stderr, "%s: unknown jail\n", optarg);
430 pcpu_stats = !pcpu_stats;
434 ps.kidle = !ps.kidle;
440 "Usage: %s [-abCHIijnPqStuvz] [-d count] [-m io | cpu] [-o field] [-s time]\n"
441 " [-J jail] [-U username] [number]\n",
442 version_string(), myname);
447 /* get count of top processes to display (if any) */
450 if ((topn = atoiwi(av[optind])) == Invalid)
453 "%s: warning: process display count should be non-negative -- using default\n",
457 #if Default_TOPN == Infinity
460 topn_specified = Yes;
465 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
469 /* repeat only if we really did the preset arguments */
472 /* set constants for username/uid display correctly */
475 uname_field = " UID ";
479 /* initialize the kernel memory interface */
480 if (machine_init(&statics, do_unames) == -1)
486 /* determine sorting order index, if necessary */
487 if (order_name != NULL)
489 if ((order_index = string_index(order_name, statics.order_names)) == -1)
493 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
495 fprintf(stderr, "\tTry one of these:");
496 pp = statics.order_names;
499 fprintf(stderr, " %s", *pp++);
507 #ifdef no_initialization_needed
508 /* initialize the hashing stuff */
515 /* initialize termcap */
516 init_termcap(interactive);
518 /* get the string to use for the process area header */
519 header_text = format_header(uname_field);
521 /* initialize display interface */
522 if ((max_topn = display_init(&statics)) == -1)
524 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
528 /* print warning if user requested more processes than we can display */
532 "%s: warning: this terminal can only display %d processes.\n",
537 /* adjust for topn == Infinity */
538 if (topn == Infinity)
541 * For smart terminals, infinity really means everything that can
542 * be displayed, or Largest.
543 * On dumb terminals, infinity means every process in the system!
544 * We only really want to do that if it was explicitly specified.
545 * This is always the case when "Default_TOPN != Infinity". But if
546 * topn wasn't explicitly specified and we are on a dumb terminal
547 * and the default is Infinity, then (and only then) we use
548 * "Nominal_TOPN" instead.
550 #if Default_TOPN == Infinity
551 topn = smart_terminal ? Largest :
552 (topn_specified ? Largest : Nominal_TOPN);
558 /* set header display accordingly */
559 display_header(topn > 0);
561 /* determine interactive state */
562 if (interactive == Maybe)
564 interactive = smart_terminal;
567 /* if # of displays not specified, fill it in */
570 displays = smart_terminal ? Infinity : 1;
573 /* hold interrupt signals while setting up the screen and the handlers */
579 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
582 (void) signal(SIGINT, leave);
583 (void) signal(SIGQUIT, leave);
584 (void) signal(SIGTSTP, tstop);
586 (void) signal(SIGWINCH, winch);
593 (void) sigsetmask(old_sigmask);
597 fputs("....", stderr);
598 fflush(stderr); /* why must I do this? */
599 sleep((unsigned)(3 * warnings));
606 * main loop -- repeat while display count is positive or while it
607 * indicates infinity (by being -1)
610 while ((displays == -1) || (displays-- > 0))
615 /* get the current stats */
616 get_system_info(&system_info);
619 compare = compares[order_index];
621 if (displaymode == DISP_CPU)
622 compare = proc_compare;
624 compare = io_compare;
627 /* get the current set of processes */
629 get_process_info(&system_info, &ps, compare);
631 /* display the load averages */
632 (*d_loadave)(system_info.last_pid,
633 system_info.load_avg);
635 /* display the current time */
636 /* this method of getting the time SHOULD be fairly portable */
638 i_uptime(&system_info.boottime, &curr_time);
639 i_timeofday(&curr_time);
641 /* display process state breakdown */
642 (*d_procstates)(system_info.p_total,
643 system_info.procstates);
645 /* display the cpu state percentage breakdown */
646 if (dostates) /* but not the first time */
648 (*d_cpustates)(system_info.cpustates);
652 /* we'll do it next time */
664 /* display memory stats */
665 (*d_memory)(system_info.memory);
666 (*d_arc)(system_info.arc);
668 /* display swap stats */
669 (*d_swap)(system_info.swap);
671 /* handle message area */
674 /* update the header area */
675 (*d_header)(header_text);
679 /* determine number of processes to actually display */
680 /* this number will be the smallest of: active processes,
681 number user requested, number current screen accomodates */
682 active_procs = system_info.P_ACTIVE;
683 if (active_procs > topn)
687 if (active_procs > max_topn)
689 active_procs = max_topn;
692 /* now show the top "n" processes. */
693 for (i = 0; i < active_procs; i++)
695 (*d_process)(i, format_next_process(processes, get_userid,
704 /* do end-screen processing */
707 /* now, flush the output buffer */
708 if (fflush(stdout) != 0)
710 new_message(MT_standout, " Write error on stdout");
716 /* only do the rest if we have more displays to show */
719 /* switch out for new display on smart terminals */
728 d_loadave = u_loadave;
729 d_procstates = u_procstates;
730 d_cpustates = u_cpustates;
734 d_message = u_message;
736 d_process = u_process;
749 else while (no_command)
751 /* assume valid command unless told otherwise */
754 /* set up arguments for select with timeout */
756 FD_SET(0, &readfds); /* for standard input */
757 timeout.tv_sec = delay;
766 /* move to the lower left */
770 /* default the signal handler action */
771 (void) signal(SIGTSTP, SIG_DFL);
773 /* unblock the signal and send ourselves one */
777 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
779 (void) kill(0, SIGTSTP);
781 /* reset the signal handler */
782 (void) signal(SIGTSTP, tstop);
792 /* reascertain the screen dimensions */
795 /* tell display to resize */
796 max_topn = display_resize();
798 /* reset the signal handler */
799 (void) signal(SIGWINCH, winch);
806 /* wait for either input or the end of the delay period */
807 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
808 if (sel_ret < 0 && errno != EINTR)
815 /* something to read -- clear the message area first */
818 /* now read it and convert to command strchr */
819 /* (use "change" as a temporary to hold strchr) */
820 if (read(0, &ch, 1) != 1)
822 /* read error: either 0 or -1 */
823 new_message(MT_standout, " Read error on stdin");
828 if ((iptr = strchr(command_chars, ch)) == NULL)
830 if (ch != '\r' && ch != '\n')
832 /* illegal command */
833 new_message(MT_standout, " Command not understood");
840 change = iptr - command_chars;
841 if (overstrike && change > CMD_OSLIMIT)
844 new_message(MT_standout,
845 " Command cannot be handled by this terminal");
851 case CMD_redraw: /* redraw screen */
855 case CMD_update: /* merely update display */
856 /* is the load average high? */
857 if (system_info.load_avg[0] > LoadMax)
859 /* yes, go home for visual feedback */
865 case CMD_quit: /* quit */
870 case CMD_help1: /* help */
875 standout("Hit any key to continue: ");
877 (void) read(0, &ch, 1);
880 case CMD_errors: /* show errors */
881 if (error_count() == 0)
883 new_message(MT_standout,
884 " Currently no errors to report.");
893 standout("Hit any key to continue: ");
895 (void) read(0, &ch, 1);
899 case CMD_number1: /* new number */
901 new_message(MT_standout,
902 "Number of processes to show: ");
903 newval = readline(tempbuf1, 8, Yes);
906 if (newval > max_topn)
908 new_message(MT_standout | MT_delayed,
909 " This terminal can only display %d processes.",
916 /* inhibit the header */
919 else if (newval > topn && topn == 0)
921 /* redraw the header */
929 case CMD_delay: /* new seconds delay */
930 new_message(MT_standout, "Seconds to delay: ");
931 if ((i = readline(tempbuf1, 8, Yes)) > -1)
933 if ((delay = i) == 0 && getuid() != 0)
941 case CMD_displays: /* change display count */
942 new_message(MT_standout,
943 "Displays to show (currently %s): ",
944 displays == -1 ? "infinite" :
946 if ((i = readline(tempbuf1, 10, Yes)) > 0)
957 case CMD_kill: /* kill program */
958 new_message(0, "kill ");
959 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
961 if ((errmsg = kill_procs(tempbuf2)) != NULL)
963 new_message(MT_standout, "%s", errmsg);
974 case CMD_renice: /* renice program */
975 new_message(0, "renice ");
976 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
978 if ((errmsg = renice_procs(tempbuf2)) != NULL)
980 new_message(MT_standout, "%s", errmsg);
994 new_message(MT_standout | MT_delayed,
995 " %sisplaying idle processes.",
996 ps.idle ? "D" : "Not d");
1001 ps.self = (ps.self == -1) ? getpid() : -1;
1002 new_message(MT_standout | MT_delayed,
1003 " %sisplaying self.",
1004 (ps.self == -1) ? "D" : "Not d");
1009 new_message(MT_standout,
1010 "Username to show (+ for all): ");
1011 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1013 if (tempbuf2[0] == '+' &&
1014 tempbuf2[1] == '\0')
1018 else if ((i = userid(tempbuf2)) == -1)
1020 new_message(MT_standout,
1021 " %s: unknown user", tempbuf2);
1037 ps.thread = !ps.thread;
1038 new_message(MT_standout | MT_delayed,
1039 " Displaying threads %s",
1040 ps.thread ? "separately" : "as a count");
1041 header_text = format_header(uname_field);
1047 new_message(MT_standout | MT_delayed,
1048 " Displaying %s CPU",
1049 ps.wcpu ? "weighted" : "raw");
1050 header_text = format_header(uname_field);
1055 if (++displaymode == DISP_MAX)
1057 header_text = format_header(uname_field);
1058 display_header(Yes);
1059 d_header = i_header;
1063 ps.system = !ps.system;
1066 fmt_flags ^= FMT_SHOWARGS;
1070 new_message(MT_standout,
1072 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1074 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1076 new_message(MT_standout,
1077 " %s: unrecognized sorting order", tempbuf2);
1094 new_message(MT_standout | MT_delayed,
1095 " %sisplaying jail ID.",
1096 ps.jail ? "D" : "Not d");
1097 header_text = format_header(uname_field);
1103 new_message(MT_standout,
1104 "Jail to show (+ for all): ");
1105 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1107 if (tempbuf2[0] == '+' &&
1108 tempbuf2[1] == '\0')
1112 else if ((i = jail_getid(tempbuf2)) == -1)
1114 new_message(MT_standout,
1115 " %s: unknown jail", tempbuf2);
1124 new_message(MT_standout |
1125 MT_delayed, " Displaying jail "
1128 format_header(uname_field);
1140 ps.kidle = !ps.kidle;
1141 new_message(MT_standout | MT_delayed,
1142 " %sisplaying system idle process.",
1143 ps.kidle ? "D" : "Not d");
1147 pcpu_stats = !pcpu_stats;
1148 new_message(MT_standout | MT_delayed,
1149 " Displaying %sCPU statistics.",
1150 pcpu_stats ? "per-" : "global ");
1152 max_topn = display_updatecpus(&statics);
1157 new_message(MT_standout, " BAD CASE IN SWITCH!");
1162 /* flush out stuff that may have been written */
1177 * reset_display() - reset all the display routine pointers so that entire
1178 * screen will get redrawn.
1184 d_loadave = i_loadave;
1185 d_procstates = i_procstates;
1186 d_cpustates = i_cpustates;
1187 d_memory = i_memory;
1190 d_message = i_message;
1191 d_header = i_header;
1192 d_process = i_process;
1199 sigret_t leave() /* exit under normal conditions -- INT handler */
1205 sigret_t tstop(i) /* SIGTSTP handler */
1214 sigret_t winch(i) /* SIGWINCH handler */
1223 void quit(status) /* exit under duress */