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
43 /* includes specific to top */
44 #include "display.h" /* interface to display package */
45 #include "screen.h" /* interface to screen package */
47 #include "top.local.h"
52 /* Size of the stdio buffer given to stdout */
53 #define Buffersize 2048
55 /* The buffer that stdio will use */
56 char stdoutbuf[Buffersize];
58 /* build Signal masks */
59 #define Smask(s) (1 << ((s) - 1))
65 /* imported from screen.c */
66 extern int overstrike;
68 static int fmt_flags = 0;
71 /* signal handling routines */
78 volatile sig_atomic_t leaveflag;
79 volatile sig_atomic_t tstopflag;
80 volatile sig_atomic_t winchflag;
82 /* internal routines */
85 /* values which need to be accessed by signal handlers */
86 static int max_topn; /* maximum displayable processes */
88 /* miscellaneous things */
89 struct process_select ps;
93 /* routines that don't return int */
101 extern int (*compares[])();
103 extern int proc_compare();
104 extern int io_compare();
108 caddr_t get_process_info();
110 /* different routines for displaying the user's identification */
111 /* (values assigned to get_userid) */
115 /* display routines that need to be predeclared */
133 /* pointers to display routines */
134 int (*d_loadave)() = i_loadave;
135 int (*d_procstates)() = i_procstates;
136 int (*d_cpustates)() = i_cpustates;
137 int (*d_memory)() = i_memory;
138 int (*d_swap)() = i_swap;
139 int (*d_message)() = i_message;
140 int (*d_header)() = i_header;
141 int (*d_process)() = i_process;
151 register int active_procs;
154 struct system_info system_info;
155 struct statics statics;
158 static char tempbuf1[50];
159 static char tempbuf2[50];
160 int old_sigmask; /* only used for BSD-style signals */
161 int topn = Default_TOPN;
162 int delay = Default_DELAY;
163 int displays = 0; /* indicates unspecified */
166 char *(*get_userid)() = username;
167 char *uname_field = "USERNAME";
175 char do_unames = Yes;
176 char interactive = Maybe;
178 #if Default_TOPN == Infinity
179 char topn_specified = No;
184 struct timeval timeout;
186 char *order_name = NULL;
190 /* FD_SET and friends are not present: fake it */
192 #define FD_ZERO(x) (*(x) = 0)
193 #define FD_SET(f, x) (*(x) = 1<<f)
198 static char command_chars[] = "\f qh?en#sdkriIutHmSCajzPo";
200 static char command_chars[] = "\f qh?en#sdkriIutHmSCajzP";
202 /* these defines enumerate the "strchr"s of the commands in command_chars */
208 #define CMD_OSLIMIT 4 /* terminals with OS can only handle commands */
209 #define CMD_errors 5 /* less than or equal to CMD_OSLIMIT */
210 #define CMD_number1 6
211 #define CMD_number2 7
213 #define CMD_displays 9
215 #define CMD_renice 11
216 #define CMD_idletog 12
217 #define CMD_idletog2 13
219 #define CMD_selftog 15
220 #define CMD_thrtog 16
221 #define CMD_viewtog 17
222 #define CMD_viewsys 18
223 #define CMD_wcputog 19
224 #define CMD_showargs 20
225 #define CMD_jidtog 21
226 #define CMD_kidletog 22
227 #define CMD_pcputog 23
232 /* set the buffer for stdout */
235 debug = fopen("debug.run", "w");
236 setbuffer(stdout, NULL, 0);
238 setbuffer(stdout, stdoutbuf, Buffersize);
244 if ((myname = strrchr(argv[0], '/')) == 0)
254 /* initialize some selection options */
265 /* get preset options from the environment */
266 if ((env_top = getenv("TOP")) != NULL)
268 av = preset_argv = argparse(env_top, &preset_argc);
271 /* set the dummy argument to an explanatory message, in case
272 getopt encounters a bad argument */
273 preset_argv[0] = "while processing environment";
276 /* process options */
278 /* if we're done doing the presets, then process the real arguments */
279 if (preset_argc == 0)
284 /* this should keep getopt happy... */
288 while ((i = getopt(ac, av, "CSIHPabijnquvzs:d:U:m:o:t")) != EOF)
292 case 'v': /* show version number */
293 fprintf(stderr, "%s: version %s\n",
294 myname, version_string());
298 case 'u': /* toggle uid/username display */
299 do_unames = !do_unames;
302 case 'U': /* display only username's processes */
303 if ((ps.uid = userid(optarg)) == -1)
305 fprintf(stderr, "%s: unknown user\n", optarg);
310 case 'S': /* show system processes */
311 ps.system = !ps.system;
314 case 'I': /* show idle processes */
318 case 'i': /* go interactive regardless */
322 case 'n': /* batch, or non-interactive */
328 fmt_flags ^= FMT_SHOWARGS;
331 case 'd': /* number of displays to show */
332 if ((i = atoiwi(optarg)) == Invalid || i == 0)
335 "%s: warning: display count should be positive -- option ignored\n",
346 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
349 "%s: warning: seconds delay should be positive -- using default\n",
351 delay = Default_DELAY;
356 case 'q': /* be quick about it */
357 /* only allow this if user is really root */
360 /* be very un-nice! */
366 "%s: warning: `-q' option can only be used by root\n",
372 case 'm': /* select display mode */
373 if (strcmp(optarg, "io") == 0) {
374 displaymode = DISP_IO;
375 } else if (strcmp(optarg, "cpu") == 0) {
376 displaymode = DISP_CPU;
379 "%s: warning: `-m' option can only take args "
386 case 'o': /* select sort order */
391 "%s: this platform does not support arbitrary ordering. Sorry.\n",
398 ps.self = (ps.self == -1) ? getpid() : -1;
406 ps.thread = !ps.thread;
414 pcpu_stats = !pcpu_stats;
418 ps.kidle = !ps.kidle;
424 "Usage: %s [-abCHIijnPqStuvz] [-d count] [-m io | cpu] [-o field] [-s time]\n"
425 " [-U username] [number]\n",
426 version_string(), myname);
431 /* get count of top processes to display (if any) */
434 if ((topn = atoiwi(av[optind])) == Invalid)
437 "%s: warning: process display count should be non-negative -- using default\n",
441 #if Default_TOPN == Infinity
444 topn_specified = Yes;
449 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
453 /* repeat only if we really did the preset arguments */
456 /* set constants for username/uid display correctly */
459 uname_field = " UID ";
463 /* initialize the kernel memory interface */
464 if (machine_init(&statics, do_unames) == -1)
470 /* determine sorting order index, if necessary */
471 if (order_name != NULL)
473 if ((order_index = string_index(order_name, statics.order_names)) == -1)
477 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
479 fprintf(stderr, "\tTry one of these:");
480 pp = statics.order_names;
483 fprintf(stderr, " %s", *pp++);
491 #ifdef no_initialization_needed
492 /* initialize the hashing stuff */
499 /* initialize termcap */
500 init_termcap(interactive);
502 /* get the string to use for the process area header */
503 header_text = format_header(uname_field);
505 /* initialize display interface */
506 if ((max_topn = display_init(&statics)) == -1)
508 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
512 /* print warning if user requested more processes than we can display */
516 "%s: warning: this terminal can only display %d processes.\n",
521 /* adjust for topn == Infinity */
522 if (topn == Infinity)
525 * For smart terminals, infinity really means everything that can
526 * be displayed, or Largest.
527 * On dumb terminals, infinity means every process in the system!
528 * We only really want to do that if it was explicitly specified.
529 * This is always the case when "Default_TOPN != Infinity". But if
530 * topn wasn't explicitly specified and we are on a dumb terminal
531 * and the default is Infinity, then (and only then) we use
532 * "Nominal_TOPN" instead.
534 #if Default_TOPN == Infinity
535 topn = smart_terminal ? Largest :
536 (topn_specified ? Largest : Nominal_TOPN);
542 /* set header display accordingly */
543 display_header(topn > 0);
545 /* determine interactive state */
546 if (interactive == Maybe)
548 interactive = smart_terminal;
551 /* if # of displays not specified, fill it in */
554 displays = smart_terminal ? Infinity : 1;
557 /* hold interrupt signals while setting up the screen and the handlers */
563 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
566 (void) signal(SIGINT, leave);
567 (void) signal(SIGQUIT, leave);
568 (void) signal(SIGTSTP, tstop);
570 (void) signal(SIGWINCH, winch);
577 (void) sigsetmask(old_sigmask);
581 fputs("....", stderr);
582 fflush(stderr); /* why must I do this? */
583 sleep((unsigned)(3 * warnings));
590 * main loop -- repeat while display count is positive or while it
591 * indicates infinity (by being -1)
594 while ((displays == -1) || (displays-- > 0))
599 /* get the current stats */
600 get_system_info(&system_info);
603 compare = compares[order_index];
605 if (displaymode == DISP_CPU)
606 compare = proc_compare;
608 compare = io_compare;
611 /* get the current set of processes */
613 get_process_info(&system_info, &ps, compare);
615 /* display the load averages */
616 (*d_loadave)(system_info.last_pid,
617 system_info.load_avg);
619 /* display the current time */
620 /* this method of getting the time SHOULD be fairly portable */
622 i_uptime(&system_info.boottime, &curr_time);
623 i_timeofday(&curr_time);
625 /* display process state breakdown */
626 (*d_procstates)(system_info.p_total,
627 system_info.procstates);
629 /* display the cpu state percentage breakdown */
630 if (dostates) /* but not the first time */
632 (*d_cpustates)(system_info.cpustates);
636 /* we'll do it next time */
648 /* display memory stats */
649 (*d_memory)(system_info.memory);
651 /* display swap stats */
652 (*d_swap)(system_info.swap);
654 /* handle message area */
657 /* update the header area */
658 (*d_header)(header_text);
662 /* determine number of processes to actually display */
663 /* this number will be the smallest of: active processes,
664 number user requested, number current screen accomodates */
665 active_procs = system_info.P_ACTIVE;
666 if (active_procs > topn)
670 if (active_procs > max_topn)
672 active_procs = max_topn;
675 /* now show the top "n" processes. */
676 for (i = 0; i < active_procs; i++)
678 (*d_process)(i, format_next_process(processes, get_userid,
687 /* do end-screen processing */
690 /* now, flush the output buffer */
691 if (fflush(stdout) != 0)
693 new_message(MT_standout, " Write error on stdout");
699 /* only do the rest if we have more displays to show */
702 /* switch out for new display on smart terminals */
711 d_loadave = u_loadave;
712 d_procstates = u_procstates;
713 d_cpustates = u_cpustates;
716 d_message = u_message;
718 d_process = u_process;
731 else while (no_command)
733 /* assume valid command unless told otherwise */
736 /* set up arguments for select with timeout */
738 FD_SET(0, &readfds); /* for standard input */
739 timeout.tv_sec = delay;
748 /* move to the lower left */
752 /* default the signal handler action */
753 (void) signal(SIGTSTP, SIG_DFL);
755 /* unblock the signal and send ourselves one */
759 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
761 (void) kill(0, SIGTSTP);
763 /* reset the signal handler */
764 (void) signal(SIGTSTP, tstop);
774 /* reascertain the screen dimensions */
777 /* tell display to resize */
778 max_topn = display_resize();
780 /* reset the signal handler */
781 (void) signal(SIGWINCH, winch);
788 /* wait for either input or the end of the delay period */
789 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
790 if (sel_ret < 0 && errno != EINTR)
797 /* something to read -- clear the message area first */
800 /* now read it and convert to command strchr */
801 /* (use "change" as a temporary to hold strchr) */
802 if (read(0, &ch, 1) != 1)
804 /* read error: either 0 or -1 */
805 new_message(MT_standout, " Read error on stdin");
810 if ((iptr = strchr(command_chars, ch)) == NULL)
812 if (ch != '\r' && ch != '\n')
814 /* illegal command */
815 new_message(MT_standout, " Command not understood");
822 change = iptr - command_chars;
823 if (overstrike && change > CMD_OSLIMIT)
826 new_message(MT_standout,
827 " Command cannot be handled by this terminal");
833 case CMD_redraw: /* redraw screen */
837 case CMD_update: /* merely update display */
838 /* is the load average high? */
839 if (system_info.load_avg[0] > LoadMax)
841 /* yes, go home for visual feedback */
847 case CMD_quit: /* quit */
852 case CMD_help1: /* help */
857 standout("Hit any key to continue: ");
859 (void) read(0, &ch, 1);
862 case CMD_errors: /* show errors */
863 if (error_count() == 0)
865 new_message(MT_standout,
866 " Currently no errors to report.");
875 standout("Hit any key to continue: ");
877 (void) read(0, &ch, 1);
881 case CMD_number1: /* new number */
883 new_message(MT_standout,
884 "Number of processes to show: ");
885 newval = readline(tempbuf1, 8, Yes);
888 if (newval > max_topn)
890 new_message(MT_standout | MT_delayed,
891 " This terminal can only display %d processes.",
898 /* inhibit the header */
901 else if (newval > topn && topn == 0)
903 /* redraw the header */
911 case CMD_delay: /* new seconds delay */
912 new_message(MT_standout, "Seconds to delay: ");
913 if ((i = readline(tempbuf1, 8, Yes)) > -1)
915 if ((delay = i) == 0 && getuid() != 0)
923 case CMD_displays: /* change display count */
924 new_message(MT_standout,
925 "Displays to show (currently %s): ",
926 displays == -1 ? "infinite" :
928 if ((i = readline(tempbuf1, 10, Yes)) > 0)
939 case CMD_kill: /* kill program */
940 new_message(0, "kill ");
941 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
943 if ((errmsg = kill_procs(tempbuf2)) != NULL)
945 new_message(MT_standout, "%s", errmsg);
956 case CMD_renice: /* renice program */
957 new_message(0, "renice ");
958 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
960 if ((errmsg = renice_procs(tempbuf2)) != NULL)
962 new_message(MT_standout, "%s", errmsg);
976 new_message(MT_standout | MT_delayed,
977 " %sisplaying idle processes.",
978 ps.idle ? "D" : "Not d");
983 ps.self = (ps.self == -1) ? getpid() : -1;
984 new_message(MT_standout | MT_delayed,
985 " %sisplaying self.",
986 (ps.self == -1) ? "D" : "Not d");
991 new_message(MT_standout,
992 "Username to show: ");
993 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
995 if (tempbuf2[0] == '+' &&
1000 else if ((i = userid(tempbuf2)) == -1)
1002 new_message(MT_standout,
1003 " %s: unknown user", tempbuf2);
1019 ps.thread = !ps.thread;
1020 new_message(MT_standout | MT_delayed,
1021 " Displaying threads %s",
1022 ps.thread ? "separately" : "as a count");
1023 header_text = format_header(uname_field);
1029 new_message(MT_standout | MT_delayed,
1030 " Displaying %s CPU",
1031 ps.wcpu ? "weighted" : "raw");
1032 header_text = format_header(uname_field);
1037 if (++displaymode == DISP_MAX)
1039 header_text = format_header(uname_field);
1040 display_header(Yes);
1041 d_header = i_header;
1045 ps.system = !ps.system;
1048 fmt_flags ^= FMT_SHOWARGS;
1052 new_message(MT_standout,
1054 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1056 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1058 new_message(MT_standout,
1059 " %s: unrecognized sorting order", tempbuf2);
1076 new_message(MT_standout | MT_delayed,
1077 " %sisplaying jail ID.",
1078 ps.jail ? "D" : "Not d");
1079 header_text = format_header(uname_field);
1084 ps.kidle = !ps.kidle;
1085 new_message(MT_standout | MT_delayed,
1086 " %sisplaying system idle process.",
1087 ps.kidle ? "D" : "Not d");
1091 pcpu_stats = !pcpu_stats;
1092 new_message(MT_standout | MT_delayed,
1093 " Displaying %sCPU statistics.",
1094 pcpu_stats ? "per-" : "global ");
1096 max_topn = display_updatecpus(&statics);
1101 new_message(MT_standout, " BAD CASE IN SWITCH!");
1106 /* flush out stuff that may have been written */
1121 * reset_display() - reset all the display routine pointers so that entire
1122 * screen will get redrawn.
1128 d_loadave = i_loadave;
1129 d_procstates = i_procstates;
1130 d_cpustates = i_cpustates;
1131 d_memory = i_memory;
1133 d_message = i_message;
1134 d_header = i_header;
1135 d_process = i_process;
1142 sigret_t leave() /* exit under normal conditions -- INT handler */
1148 sigret_t tstop(i) /* SIGTSTP handler */
1157 sigret_t winch(i) /* SIGWINCH handler */
1166 void quit(status) /* exit under duress */