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#sdkriIutHmSCajzPJo";
193 static char command_chars[] = "\f qh?en#sdkriIutHmSCajzPJ";
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
226 /* set the buffer for stdout */
229 debug = fopen("debug.run", "w");
230 setbuffer(stdout, NULL, 0);
232 setbuffer(stdout, stdoutbuf, Buffersize);
238 if ((myname = strrchr(argv[0], '/')) == 0)
248 /* initialize some selection options */
260 /* get preset options from the environment */
261 if ((env_top = getenv("TOP")) != NULL)
263 av = preset_argv = argparse(env_top, &preset_argc);
266 /* set the dummy argument to an explanatory message, in case
267 getopt encounters a bad argument */
268 preset_argv[0] = "while processing environment";
271 /* process options */
273 /* if we're done doing the presets, then process the real arguments */
274 if (preset_argc == 0)
279 /* this should keep getopt happy... */
283 while ((i = getopt(ac, av, "CSIHPabijJ:nquvzs:d:U:m:o:t")) != EOF)
287 case 'v': /* show version number */
288 fprintf(stderr, "%s: version %s\n",
289 myname, version_string());
293 case 'u': /* toggle uid/username display */
294 do_unames = !do_unames;
297 case 'U': /* display only username's processes */
298 if ((ps.uid = userid(optarg)) == -1)
300 fprintf(stderr, "%s: unknown user\n", optarg);
305 case 'S': /* show system processes */
306 ps.system = !ps.system;
309 case 'I': /* show idle processes */
313 case 'i': /* go interactive regardless */
317 case 'n': /* batch, or non-interactive */
323 fmt_flags ^= FMT_SHOWARGS;
326 case 'd': /* number of displays to show */
327 if ((i = atoiwi(optarg)) == Invalid || i == 0)
330 "%s: warning: display count should be positive -- option ignored\n",
341 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
344 "%s: warning: seconds delay should be positive -- using default\n",
346 delay = Default_DELAY;
351 case 'q': /* be quick about it */
352 /* only allow this if user is really root */
355 /* be very un-nice! */
361 "%s: warning: `-q' option can only be used by root\n",
367 case 'm': /* select display mode */
368 if (strcmp(optarg, "io") == 0) {
369 displaymode = DISP_IO;
370 } else if (strcmp(optarg, "cpu") == 0) {
371 displaymode = DISP_CPU;
374 "%s: warning: `-m' option can only take args "
381 case 'o': /* select sort order */
386 "%s: this platform does not support arbitrary ordering. Sorry.\n",
393 ps.self = (ps.self == -1) ? getpid() : -1;
401 ps.thread = !ps.thread;
408 case 'J': /* display only jail's processes */
409 if ((ps.jid = jail_getid(optarg)) == -1)
411 fprintf(stderr, "%s: unknown jail\n", optarg);
418 pcpu_stats = !pcpu_stats;
422 ps.kidle = !ps.kidle;
428 "Usage: %s [-abCHIijnPqStuvz] [-d count] [-m io | cpu] [-o field] [-s time]\n"
429 " [-J jail] [-U username] [number]\n",
430 version_string(), myname);
435 /* get count of top processes to display (if any) */
438 if ((topn = atoiwi(av[optind])) == Invalid)
441 "%s: warning: process display count should be non-negative -- using default\n",
445 #if Default_TOPN == Infinity
448 topn_specified = Yes;
453 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
457 /* repeat only if we really did the preset arguments */
460 /* set constants for username/uid display correctly */
463 uname_field = " UID ";
467 /* initialize the kernel memory interface */
468 if (machine_init(&statics, do_unames) == -1)
474 /* determine sorting order index, if necessary */
475 if (order_name != NULL)
477 if ((order_index = string_index(order_name, statics.order_names)) == -1)
481 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
483 fprintf(stderr, "\tTry one of these:");
484 pp = statics.order_names;
487 fprintf(stderr, " %s", *pp++);
495 #ifdef no_initialization_needed
496 /* initialize the hashing stuff */
503 /* initialize termcap */
504 init_termcap(interactive);
506 /* get the string to use for the process area header */
507 header_text = format_header(uname_field);
509 /* initialize display interface */
510 if ((max_topn = display_init(&statics)) == -1)
512 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
516 /* print warning if user requested more processes than we can display */
520 "%s: warning: this terminal can only display %d processes.\n",
525 /* adjust for topn == Infinity */
526 if (topn == Infinity)
529 * For smart terminals, infinity really means everything that can
530 * be displayed, or Largest.
531 * On dumb terminals, infinity means every process in the system!
532 * We only really want to do that if it was explicitly specified.
533 * This is always the case when "Default_TOPN != Infinity". But if
534 * topn wasn't explicitly specified and we are on a dumb terminal
535 * and the default is Infinity, then (and only then) we use
536 * "Nominal_TOPN" instead.
538 #if Default_TOPN == Infinity
539 topn = smart_terminal ? Largest :
540 (topn_specified ? Largest : Nominal_TOPN);
546 /* set header display accordingly */
547 display_header(topn > 0);
549 /* determine interactive state */
550 if (interactive == Maybe)
552 interactive = smart_terminal;
555 /* if # of displays not specified, fill it in */
558 displays = smart_terminal ? Infinity : 1;
561 /* hold interrupt signals while setting up the screen and the handlers */
567 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
570 (void) signal(SIGINT, leave);
571 (void) signal(SIGQUIT, leave);
572 (void) signal(SIGTSTP, tstop);
574 (void) signal(SIGWINCH, winch);
581 (void) sigsetmask(old_sigmask);
585 fputs("....", stderr);
586 fflush(stderr); /* why must I do this? */
587 sleep((unsigned)(3 * warnings));
594 * main loop -- repeat while display count is positive or while it
595 * indicates infinity (by being -1)
598 while ((displays == -1) || (displays-- > 0))
603 /* get the current stats */
604 get_system_info(&system_info);
607 compare = compares[order_index];
609 if (displaymode == DISP_CPU)
610 compare = proc_compare;
612 compare = io_compare;
615 /* get the current set of processes */
617 get_process_info(&system_info, &ps, compare);
619 /* display the load averages */
620 (*d_loadave)(system_info.last_pid,
621 system_info.load_avg);
623 /* display the current time */
624 /* this method of getting the time SHOULD be fairly portable */
626 i_uptime(&system_info.boottime, &curr_time);
627 i_timeofday(&curr_time);
629 /* display process state breakdown */
630 (*d_procstates)(system_info.p_total,
631 system_info.procstates);
633 /* display the cpu state percentage breakdown */
634 if (dostates) /* but not the first time */
636 (*d_cpustates)(system_info.cpustates);
640 /* we'll do it next time */
652 /* display memory stats */
653 (*d_memory)(system_info.memory);
654 (*d_arc)(system_info.arc);
656 /* display swap stats */
657 (*d_swap)(system_info.swap);
659 /* handle message area */
662 /* update the header area */
663 (*d_header)(header_text);
667 /* determine number of processes to actually display */
668 /* this number will be the smallest of: active processes,
669 number user requested, number current screen accomodates */
670 active_procs = system_info.P_ACTIVE;
671 if (active_procs > topn)
675 if (active_procs > max_topn)
677 active_procs = max_topn;
680 /* now show the top "n" processes. */
681 for (i = 0; i < active_procs; i++)
683 (*d_process)(i, format_next_process(processes, get_userid,
692 /* do end-screen processing */
695 /* now, flush the output buffer */
696 if (fflush(stdout) != 0)
698 new_message(MT_standout, " Write error on stdout");
704 /* only do the rest if we have more displays to show */
707 /* switch out for new display on smart terminals */
716 d_loadave = u_loadave;
717 d_procstates = u_procstates;
718 d_cpustates = u_cpustates;
722 d_message = u_message;
724 d_process = u_process;
737 else while (no_command)
739 /* assume valid command unless told otherwise */
742 /* set up arguments for select with timeout */
744 FD_SET(0, &readfds); /* for standard input */
745 timeout.tv_sec = delay;
754 /* move to the lower left */
758 /* default the signal handler action */
759 (void) signal(SIGTSTP, SIG_DFL);
761 /* unblock the signal and send ourselves one */
765 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
767 (void) kill(0, SIGTSTP);
769 /* reset the signal handler */
770 (void) signal(SIGTSTP, tstop);
780 /* reascertain the screen dimensions */
783 /* tell display to resize */
784 max_topn = display_resize();
786 /* reset the signal handler */
787 (void) signal(SIGWINCH, winch);
794 /* wait for either input or the end of the delay period */
795 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
796 if (sel_ret < 0 && errno != EINTR)
803 /* something to read -- clear the message area first */
806 /* now read it and convert to command strchr */
807 /* (use "change" as a temporary to hold strchr) */
808 if (read(0, &ch, 1) != 1)
810 /* read error: either 0 or -1 */
811 new_message(MT_standout, " Read error on stdin");
816 if ((iptr = strchr(command_chars, ch)) == NULL)
818 if (ch != '\r' && ch != '\n')
820 /* illegal command */
821 new_message(MT_standout, " Command not understood");
828 change = iptr - command_chars;
829 if (overstrike && change > CMD_OSLIMIT)
832 new_message(MT_standout,
833 " Command cannot be handled by this terminal");
839 case CMD_redraw: /* redraw screen */
843 case CMD_update: /* merely update display */
844 /* is the load average high? */
845 if (system_info.load_avg[0] > LoadMax)
847 /* yes, go home for visual feedback */
853 case CMD_quit: /* quit */
858 case CMD_help1: /* help */
863 standout("Hit any key to continue: ");
865 (void) read(0, &ch, 1);
868 case CMD_errors: /* show errors */
869 if (error_count() == 0)
871 new_message(MT_standout,
872 " Currently no errors to report.");
881 standout("Hit any key to continue: ");
883 (void) read(0, &ch, 1);
887 case CMD_number1: /* new number */
889 new_message(MT_standout,
890 "Number of processes to show: ");
891 newval = readline(tempbuf1, 8, Yes);
894 if (newval > max_topn)
896 new_message(MT_standout | MT_delayed,
897 " This terminal can only display %d processes.",
904 /* inhibit the header */
907 else if (newval > topn && topn == 0)
909 /* redraw the header */
917 case CMD_delay: /* new seconds delay */
918 new_message(MT_standout, "Seconds to delay: ");
919 if ((i = readline(tempbuf1, 8, Yes)) > -1)
921 if ((delay = i) == 0 && getuid() != 0)
929 case CMD_displays: /* change display count */
930 new_message(MT_standout,
931 "Displays to show (currently %s): ",
932 displays == -1 ? "infinite" :
934 if ((i = readline(tempbuf1, 10, Yes)) > 0)
945 case CMD_kill: /* kill program */
946 new_message(0, "kill ");
947 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
949 if ((errmsg = kill_procs(tempbuf2)) != NULL)
951 new_message(MT_standout, "%s", errmsg);
962 case CMD_renice: /* renice program */
963 new_message(0, "renice ");
964 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
966 if ((errmsg = renice_procs(tempbuf2)) != NULL)
968 new_message(MT_standout, "%s", errmsg);
982 new_message(MT_standout | MT_delayed,
983 " %sisplaying idle processes.",
984 ps.idle ? "D" : "Not d");
989 ps.self = (ps.self == -1) ? getpid() : -1;
990 new_message(MT_standout | MT_delayed,
991 " %sisplaying self.",
992 (ps.self == -1) ? "D" : "Not d");
997 new_message(MT_standout,
998 "Username to show (+ for all): ");
999 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1001 if (tempbuf2[0] == '+' &&
1002 tempbuf2[1] == '\0')
1006 else if ((i = userid(tempbuf2)) == -1)
1008 new_message(MT_standout,
1009 " %s: unknown user", tempbuf2);
1025 ps.thread = !ps.thread;
1026 new_message(MT_standout | MT_delayed,
1027 " Displaying threads %s",
1028 ps.thread ? "separately" : "as a count");
1029 header_text = format_header(uname_field);
1035 new_message(MT_standout | MT_delayed,
1036 " Displaying %s CPU",
1037 ps.wcpu ? "weighted" : "raw");
1038 header_text = format_header(uname_field);
1043 if (++displaymode == DISP_MAX)
1045 header_text = format_header(uname_field);
1046 display_header(Yes);
1047 d_header = i_header;
1051 ps.system = !ps.system;
1054 fmt_flags ^= FMT_SHOWARGS;
1058 new_message(MT_standout,
1060 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1062 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1064 new_message(MT_standout,
1065 " %s: unrecognized sorting order", tempbuf2);
1082 new_message(MT_standout | MT_delayed,
1083 " %sisplaying jail ID.",
1084 ps.jail ? "D" : "Not d");
1085 header_text = format_header(uname_field);
1091 new_message(MT_standout,
1092 "Jail to show (+ for all): ");
1093 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1095 if (tempbuf2[0] == '+' &&
1096 tempbuf2[1] == '\0')
1100 else if ((i = jail_getid(tempbuf2)) == -1)
1102 new_message(MT_standout,
1103 " %s: unknown jail", tempbuf2);
1112 new_message(MT_standout |
1113 MT_delayed, " Displaying jail "
1116 format_header(uname_field);
1128 ps.kidle = !ps.kidle;
1129 new_message(MT_standout | MT_delayed,
1130 " %sisplaying system idle process.",
1131 ps.kidle ? "D" : "Not d");
1135 pcpu_stats = !pcpu_stats;
1136 new_message(MT_standout | MT_delayed,
1137 " Displaying %sCPU statistics.",
1138 pcpu_stats ? "per-" : "global ");
1140 max_topn = display_updatecpus(&statics);
1145 new_message(MT_standout, " BAD CASE IN SWITCH!");
1150 /* flush out stuff that may have been written */
1165 * reset_display() - reset all the display routine pointers so that entire
1166 * screen will get redrawn.
1173 d_loadave = i_loadave;
1174 d_procstates = i_procstates;
1175 d_cpustates = i_cpustates;
1176 d_memory = i_memory;
1179 d_message = i_message;
1180 d_header = i_header;
1181 d_process = i_process;
1188 sigret_t leave() /* exit under normal conditions -- INT handler */
1194 sigret_t tstop(i) /* SIGTSTP handler */
1203 sigret_t winch(i) /* SIGWINCH handler */
1212 void quit(status) /* exit under duress */