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 */
135 /* pointers to display routines */
136 int (*d_loadave)() = i_loadave;
137 int (*d_procstates)() = i_procstates;
138 int (*d_cpustates)() = i_cpustates;
139 int (*d_memory)() = i_memory;
140 int (*d_arc)() = i_arc;
141 int (*d_swap)() = i_swap;
142 int (*d_message)() = i_message;
143 int (*d_header)() = i_header;
144 int (*d_process)() = i_process;
154 register int active_procs;
157 struct system_info system_info;
158 struct statics statics;
161 static char tempbuf1[50];
162 static char tempbuf2[50];
163 int old_sigmask; /* only used for BSD-style signals */
164 int topn = Default_TOPN;
165 int delay = Default_DELAY;
166 int displays = 0; /* indicates unspecified */
169 char *(*get_userid)() = username;
170 char *uname_field = "USERNAME";
178 char do_unames = Yes;
179 char interactive = Maybe;
181 #if Default_TOPN == Infinity
182 char topn_specified = No;
187 struct timeval timeout;
189 char *order_name = NULL;
193 /* FD_SET and friends are not present: fake it */
195 #define FD_ZERO(x) (*(x) = 0)
196 #define FD_SET(f, x) (*(x) = 1<<f)
201 static char command_chars[] = "\f qh?en#sdkriIutHmSCajzPo";
203 static char command_chars[] = "\f qh?en#sdkriIutHmSCajzP";
205 /* these defines enumerate the "strchr"s of the commands in command_chars */
211 #define CMD_OSLIMIT 4 /* terminals with OS can only handle commands */
212 #define CMD_errors 5 /* less than or equal to CMD_OSLIMIT */
213 #define CMD_number1 6
214 #define CMD_number2 7
216 #define CMD_displays 9
218 #define CMD_renice 11
219 #define CMD_idletog 12
220 #define CMD_idletog2 13
222 #define CMD_selftog 15
223 #define CMD_thrtog 16
224 #define CMD_viewtog 17
225 #define CMD_viewsys 18
226 #define CMD_wcputog 19
227 #define CMD_showargs 20
228 #define CMD_jidtog 21
229 #define CMD_kidletog 22
230 #define CMD_pcputog 23
235 /* set the buffer for stdout */
238 debug = fopen("debug.run", "w");
239 setbuffer(stdout, NULL, 0);
241 setbuffer(stdout, stdoutbuf, Buffersize);
247 if ((myname = strrchr(argv[0], '/')) == 0)
257 /* initialize some selection options */
268 /* get preset options from the environment */
269 if ((env_top = getenv("TOP")) != NULL)
271 av = preset_argv = argparse(env_top, &preset_argc);
274 /* set the dummy argument to an explanatory message, in case
275 getopt encounters a bad argument */
276 preset_argv[0] = "while processing environment";
279 /* process options */
281 /* if we're done doing the presets, then process the real arguments */
282 if (preset_argc == 0)
287 /* this should keep getopt happy... */
291 while ((i = getopt(ac, av, "CSIHPabijnquvzs:d:U:m:o:t")) != EOF)
295 case 'v': /* show version number */
296 fprintf(stderr, "%s: version %s\n",
297 myname, version_string());
301 case 'u': /* toggle uid/username display */
302 do_unames = !do_unames;
305 case 'U': /* display only username's processes */
306 if ((ps.uid = userid(optarg)) == -1)
308 fprintf(stderr, "%s: unknown user\n", optarg);
313 case 'S': /* show system processes */
314 ps.system = !ps.system;
317 case 'I': /* show idle processes */
321 case 'i': /* go interactive regardless */
325 case 'n': /* batch, or non-interactive */
331 fmt_flags ^= FMT_SHOWARGS;
334 case 'd': /* number of displays to show */
335 if ((i = atoiwi(optarg)) == Invalid || i == 0)
338 "%s: warning: display count should be positive -- option ignored\n",
349 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
352 "%s: warning: seconds delay should be positive -- using default\n",
354 delay = Default_DELAY;
359 case 'q': /* be quick about it */
360 /* only allow this if user is really root */
363 /* be very un-nice! */
369 "%s: warning: `-q' option can only be used by root\n",
375 case 'm': /* select display mode */
376 if (strcmp(optarg, "io") == 0) {
377 displaymode = DISP_IO;
378 } else if (strcmp(optarg, "cpu") == 0) {
379 displaymode = DISP_CPU;
382 "%s: warning: `-m' option can only take args "
389 case 'o': /* select sort order */
394 "%s: this platform does not support arbitrary ordering. Sorry.\n",
401 ps.self = (ps.self == -1) ? getpid() : -1;
409 ps.thread = !ps.thread;
417 pcpu_stats = !pcpu_stats;
421 ps.kidle = !ps.kidle;
427 "Usage: %s [-abCHIijnPqStuvz] [-d count] [-m io | cpu] [-o field] [-s time]\n"
428 " [-U username] [number]\n",
429 version_string(), myname);
434 /* get count of top processes to display (if any) */
437 if ((topn = atoiwi(av[optind])) == Invalid)
440 "%s: warning: process display count should be non-negative -- using default\n",
444 #if Default_TOPN == Infinity
447 topn_specified = Yes;
452 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
456 /* repeat only if we really did the preset arguments */
459 /* set constants for username/uid display correctly */
462 uname_field = " UID ";
466 /* initialize the kernel memory interface */
467 if (machine_init(&statics, do_unames) == -1)
473 /* determine sorting order index, if necessary */
474 if (order_name != NULL)
476 if ((order_index = string_index(order_name, statics.order_names)) == -1)
480 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
482 fprintf(stderr, "\tTry one of these:");
483 pp = statics.order_names;
486 fprintf(stderr, " %s", *pp++);
494 #ifdef no_initialization_needed
495 /* initialize the hashing stuff */
502 /* initialize termcap */
503 init_termcap(interactive);
505 /* get the string to use for the process area header */
506 header_text = format_header(uname_field);
508 /* initialize display interface */
509 if ((max_topn = display_init(&statics)) == -1)
511 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
515 /* print warning if user requested more processes than we can display */
519 "%s: warning: this terminal can only display %d processes.\n",
524 /* adjust for topn == Infinity */
525 if (topn == Infinity)
528 * For smart terminals, infinity really means everything that can
529 * be displayed, or Largest.
530 * On dumb terminals, infinity means every process in the system!
531 * We only really want to do that if it was explicitly specified.
532 * This is always the case when "Default_TOPN != Infinity". But if
533 * topn wasn't explicitly specified and we are on a dumb terminal
534 * and the default is Infinity, then (and only then) we use
535 * "Nominal_TOPN" instead.
537 #if Default_TOPN == Infinity
538 topn = smart_terminal ? Largest :
539 (topn_specified ? Largest : Nominal_TOPN);
545 /* set header display accordingly */
546 display_header(topn > 0);
548 /* determine interactive state */
549 if (interactive == Maybe)
551 interactive = smart_terminal;
554 /* if # of displays not specified, fill it in */
557 displays = smart_terminal ? Infinity : 1;
560 /* hold interrupt signals while setting up the screen and the handlers */
566 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
569 (void) signal(SIGINT, leave);
570 (void) signal(SIGQUIT, leave);
571 (void) signal(SIGTSTP, tstop);
573 (void) signal(SIGWINCH, winch);
580 (void) sigsetmask(old_sigmask);
584 fputs("....", stderr);
585 fflush(stderr); /* why must I do this? */
586 sleep((unsigned)(3 * warnings));
593 * main loop -- repeat while display count is positive or while it
594 * indicates infinity (by being -1)
597 while ((displays == -1) || (displays-- > 0))
602 /* get the current stats */
603 get_system_info(&system_info);
606 compare = compares[order_index];
608 if (displaymode == DISP_CPU)
609 compare = proc_compare;
611 compare = io_compare;
614 /* get the current set of processes */
616 get_process_info(&system_info, &ps, compare);
618 /* display the load averages */
619 (*d_loadave)(system_info.last_pid,
620 system_info.load_avg);
622 /* display the current time */
623 /* this method of getting the time SHOULD be fairly portable */
625 i_uptime(&system_info.boottime, &curr_time);
626 i_timeofday(&curr_time);
628 /* display process state breakdown */
629 (*d_procstates)(system_info.p_total,
630 system_info.procstates);
632 /* display the cpu state percentage breakdown */
633 if (dostates) /* but not the first time */
635 (*d_cpustates)(system_info.cpustates);
639 /* we'll do it next time */
651 /* display memory stats */
652 (*d_memory)(system_info.memory);
653 (*d_arc)(system_info.arc);
655 /* display swap stats */
656 (*d_swap)(system_info.swap);
658 /* handle message area */
661 /* update the header area */
662 (*d_header)(header_text);
666 /* determine number of processes to actually display */
667 /* this number will be the smallest of: active processes,
668 number user requested, number current screen accomodates */
669 active_procs = system_info.P_ACTIVE;
670 if (active_procs > topn)
674 if (active_procs > max_topn)
676 active_procs = max_topn;
679 /* now show the top "n" processes. */
680 for (i = 0; i < active_procs; i++)
682 (*d_process)(i, format_next_process(processes, get_userid,
691 /* do end-screen processing */
694 /* now, flush the output buffer */
695 if (fflush(stdout) != 0)
697 new_message(MT_standout, " Write error on stdout");
703 /* only do the rest if we have more displays to show */
706 /* switch out for new display on smart terminals */
715 d_loadave = u_loadave;
716 d_procstates = u_procstates;
717 d_cpustates = u_cpustates;
721 d_message = u_message;
723 d_process = u_process;
736 else while (no_command)
738 /* assume valid command unless told otherwise */
741 /* set up arguments for select with timeout */
743 FD_SET(0, &readfds); /* for standard input */
744 timeout.tv_sec = delay;
753 /* move to the lower left */
757 /* default the signal handler action */
758 (void) signal(SIGTSTP, SIG_DFL);
760 /* unblock the signal and send ourselves one */
764 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
766 (void) kill(0, SIGTSTP);
768 /* reset the signal handler */
769 (void) signal(SIGTSTP, tstop);
779 /* reascertain the screen dimensions */
782 /* tell display to resize */
783 max_topn = display_resize();
785 /* reset the signal handler */
786 (void) signal(SIGWINCH, winch);
793 /* wait for either input or the end of the delay period */
794 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
795 if (sel_ret < 0 && errno != EINTR)
802 /* something to read -- clear the message area first */
805 /* now read it and convert to command strchr */
806 /* (use "change" as a temporary to hold strchr) */
807 if (read(0, &ch, 1) != 1)
809 /* read error: either 0 or -1 */
810 new_message(MT_standout, " Read error on stdin");
815 if ((iptr = strchr(command_chars, ch)) == NULL)
817 if (ch != '\r' && ch != '\n')
819 /* illegal command */
820 new_message(MT_standout, " Command not understood");
827 change = iptr - command_chars;
828 if (overstrike && change > CMD_OSLIMIT)
831 new_message(MT_standout,
832 " Command cannot be handled by this terminal");
838 case CMD_redraw: /* redraw screen */
842 case CMD_update: /* merely update display */
843 /* is the load average high? */
844 if (system_info.load_avg[0] > LoadMax)
846 /* yes, go home for visual feedback */
852 case CMD_quit: /* quit */
857 case CMD_help1: /* help */
862 standout("Hit any key to continue: ");
864 (void) read(0, &ch, 1);
867 case CMD_errors: /* show errors */
868 if (error_count() == 0)
870 new_message(MT_standout,
871 " Currently no errors to report.");
880 standout("Hit any key to continue: ");
882 (void) read(0, &ch, 1);
886 case CMD_number1: /* new number */
888 new_message(MT_standout,
889 "Number of processes to show: ");
890 newval = readline(tempbuf1, 8, Yes);
893 if (newval > max_topn)
895 new_message(MT_standout | MT_delayed,
896 " This terminal can only display %d processes.",
903 /* inhibit the header */
906 else if (newval > topn && topn == 0)
908 /* redraw the header */
916 case CMD_delay: /* new seconds delay */
917 new_message(MT_standout, "Seconds to delay: ");
918 if ((i = readline(tempbuf1, 8, Yes)) > -1)
920 if ((delay = i) == 0 && getuid() != 0)
928 case CMD_displays: /* change display count */
929 new_message(MT_standout,
930 "Displays to show (currently %s): ",
931 displays == -1 ? "infinite" :
933 if ((i = readline(tempbuf1, 10, Yes)) > 0)
944 case CMD_kill: /* kill program */
945 new_message(0, "kill ");
946 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
948 if ((errmsg = kill_procs(tempbuf2)) != NULL)
950 new_message(MT_standout, "%s", errmsg);
961 case CMD_renice: /* renice program */
962 new_message(0, "renice ");
963 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
965 if ((errmsg = renice_procs(tempbuf2)) != NULL)
967 new_message(MT_standout, "%s", errmsg);
981 new_message(MT_standout | MT_delayed,
982 " %sisplaying idle processes.",
983 ps.idle ? "D" : "Not d");
988 ps.self = (ps.self == -1) ? getpid() : -1;
989 new_message(MT_standout | MT_delayed,
990 " %sisplaying self.",
991 (ps.self == -1) ? "D" : "Not d");
996 new_message(MT_standout,
997 "Username to show: ");
998 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1000 if (tempbuf2[0] == '+' &&
1001 tempbuf2[1] == '\0')
1005 else if ((i = userid(tempbuf2)) == -1)
1007 new_message(MT_standout,
1008 " %s: unknown user", tempbuf2);
1024 ps.thread = !ps.thread;
1025 new_message(MT_standout | MT_delayed,
1026 " Displaying threads %s",
1027 ps.thread ? "separately" : "as a count");
1028 header_text = format_header(uname_field);
1034 new_message(MT_standout | MT_delayed,
1035 " Displaying %s CPU",
1036 ps.wcpu ? "weighted" : "raw");
1037 header_text = format_header(uname_field);
1042 if (++displaymode == DISP_MAX)
1044 header_text = format_header(uname_field);
1045 display_header(Yes);
1046 d_header = i_header;
1050 ps.system = !ps.system;
1053 fmt_flags ^= FMT_SHOWARGS;
1057 new_message(MT_standout,
1059 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1061 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1063 new_message(MT_standout,
1064 " %s: unrecognized sorting order", tempbuf2);
1081 new_message(MT_standout | MT_delayed,
1082 " %sisplaying jail ID.",
1083 ps.jail ? "D" : "Not d");
1084 header_text = format_header(uname_field);
1089 ps.kidle = !ps.kidle;
1090 new_message(MT_standout | MT_delayed,
1091 " %sisplaying system idle process.",
1092 ps.kidle ? "D" : "Not d");
1096 pcpu_stats = !pcpu_stats;
1097 new_message(MT_standout | MT_delayed,
1098 " Displaying %sCPU statistics.",
1099 pcpu_stats ? "per-" : "global ");
1101 max_topn = display_updatecpus(&statics);
1106 new_message(MT_standout, " BAD CASE IN SWITCH!");
1111 /* flush out stuff that may have been written */
1126 * reset_display() - reset all the display routine pointers so that entire
1127 * screen will get redrawn.
1133 d_loadave = i_loadave;
1134 d_procstates = i_procstates;
1135 d_cpustates = i_cpustates;
1136 d_memory = i_memory;
1139 d_message = i_message;
1140 d_header = i_header;
1141 d_process = i_process;
1148 sigret_t leave() /* exit under normal conditions -- INT handler */
1154 sigret_t tstop(i) /* SIGTSTP handler */
1163 sigret_t winch(i) /* SIGWINCH handler */
1172 void quit(status) /* exit under duress */