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 */
79 volatile sig_atomic_t leaveflag;
80 volatile sig_atomic_t tstopflag;
81 volatile sig_atomic_t winchflag;
83 /* internal routines */
86 /* values which need to be accessed by signal handlers */
87 static int max_topn; /* maximum displayable processes */
89 /* miscellaneous things */
90 struct process_select ps;
94 /* routines that don't return int */
102 extern int (*compares[])();
104 extern int proc_compare();
105 extern int io_compare();
109 caddr_t get_process_info();
111 /* different routines for displaying the user's identification */
112 /* (values assigned to get_userid) */
116 /* display routines that need to be predeclared */
134 /* pointers to display routines */
135 int (*d_loadave)() = i_loadave;
136 int (*d_procstates)() = i_procstates;
137 int (*d_cpustates)() = i_cpustates;
138 int (*d_memory)() = i_memory;
139 int (*d_swap)() = i_swap;
140 int (*d_message)() = i_message;
141 int (*d_header)() = i_header;
142 int (*d_process)() = i_process;
152 register int active_procs;
155 struct system_info system_info;
156 struct statics statics;
159 static char tempbuf1[50];
160 static char tempbuf2[50];
161 int old_sigmask; /* only used for BSD-style signals */
162 int topn = Default_TOPN;
163 int delay = Default_DELAY;
164 int displays = 0; /* indicates unspecified */
167 char *(*get_userid)() = username;
168 char *uname_field = "USERNAME";
176 char do_unames = Yes;
177 char interactive = Maybe;
179 #if Default_TOPN == Infinity
180 char topn_specified = No;
185 struct timeval timeout;
187 char *order_name = NULL;
191 /* FD_SET and friends are not present: fake it */
193 #define FD_ZERO(x) (*(x) = 0)
194 #define FD_SET(f, x) (*(x) = 1<<f)
199 static char command_chars[] = "\f qh?en#sdkriIutHmSCajo";
201 static char command_chars[] = "\f qh?en#sdkriIutHmSCaj";
203 /* these defines enumerate the "strchr"s of the commands in command_chars */
209 #define CMD_OSLIMIT 4 /* terminals with OS can only handle commands */
210 #define CMD_errors 5 /* less than or equal to CMD_OSLIMIT */
211 #define CMD_number1 6
212 #define CMD_number2 7
214 #define CMD_displays 9
216 #define CMD_renice 11
217 #define CMD_idletog 12
218 #define CMD_idletog2 13
220 #define CMD_selftog 15
221 #define CMD_thrtog 16
222 #define CMD_viewtog 17
223 #define CMD_viewsys 18
224 #define CMD_wcputog 19
225 #define CMD_showargs 20
226 #define CMD_jidtog 21
231 /* set the buffer for stdout */
234 debug = fopen("debug.run", "w");
235 setbuffer(stdout, NULL, 0);
237 setbuffer(stdout, stdoutbuf, Buffersize);
243 if ((myname = strrchr(argv[0], '/')) == 0)
253 /* initialize some selection options */
263 /* get preset options from the environment */
264 if ((env_top = getenv("TOP")) != NULL)
266 av = preset_argv = argparse(env_top, &preset_argc);
269 /* set the dummy argument to an explanatory message, in case
270 getopt encounters a bad argument */
271 preset_argv[0] = "while processing environment";
274 /* process options */
276 /* if we're done doing the presets, then process the real arguments */
277 if (preset_argc == 0)
282 /* this should keep getopt happy... */
286 while ((i = getopt(ac, av, "CSIHPabijnquvs:d:U:m:o:t")) != EOF)
290 case 'v': /* show version number */
291 fprintf(stderr, "%s: version %s\n",
292 myname, version_string());
296 case 'u': /* toggle uid/username display */
297 do_unames = !do_unames;
300 case 'U': /* display only username's processes */
301 if ((ps.uid = userid(optarg)) == -1)
303 fprintf(stderr, "%s: unknown user\n", optarg);
308 case 'S': /* show system processes */
309 ps.system = !ps.system;
312 case 'I': /* show idle processes */
316 case 'i': /* go interactive regardless */
320 case 'n': /* batch, or non-interactive */
326 fmt_flags ^= FMT_SHOWARGS;
329 case 'd': /* number of displays to show */
330 if ((i = atoiwi(optarg)) == Invalid || i == 0)
333 "%s: warning: display count should be positive -- option ignored\n",
344 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
347 "%s: warning: seconds delay should be positive -- using default\n",
349 delay = Default_DELAY;
354 case 'q': /* be quick about it */
355 /* only allow this if user is really root */
358 /* be very un-nice! */
364 "%s: warning: `-q' option can only be used by root\n",
370 case 'm': /* select display mode */
371 if (strcmp(optarg, "io") == 0) {
372 displaymode = DISP_IO;
373 } else if (strcmp(optarg, "cpu") == 0) {
374 displaymode = DISP_CPU;
377 "%s: warning: `-m' option can only take args "
384 case 'o': /* select sort order */
389 "%s: this platform does not support arbitrary ordering. Sorry.\n",
396 ps.self = (ps.self == -1) ? getpid() : -1;
404 ps.thread = !ps.thread;
418 "Usage: %s [-abCHIijnPqStuv] [-d count] [-m io | cpu] [-o field] [-s time]\n"
419 " [-U username] [number]\n",
420 version_string(), myname);
425 /* get count of top processes to display (if any) */
428 if ((topn = atoiwi(av[optind])) == Invalid)
431 "%s: warning: process display count should be non-negative -- using default\n",
435 #if Default_TOPN == Infinity
438 topn_specified = Yes;
443 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
447 /* repeat only if we really did the preset arguments */
450 /* set constants for username/uid display correctly */
453 uname_field = " UID ";
457 /* initialize the kernel memory interface */
458 if (machine_init(&statics, do_unames) == -1)
464 /* determine sorting order index, if necessary */
465 if (order_name != NULL)
467 if ((order_index = string_index(order_name, statics.order_names)) == -1)
471 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
473 fprintf(stderr, "\tTry one of these:");
474 pp = statics.order_names;
477 fprintf(stderr, " %s", *pp++);
485 #ifdef no_initialization_needed
486 /* initialize the hashing stuff */
493 /* initialize termcap */
494 init_termcap(interactive);
496 /* get the string to use for the process area header */
497 header_text = format_header(uname_field);
499 /* initialize display interface */
500 if ((max_topn = display_init(&statics)) == -1)
502 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
506 /* print warning if user requested more processes than we can display */
510 "%s: warning: this terminal can only display %d processes.\n",
515 /* adjust for topn == Infinity */
516 if (topn == Infinity)
519 * For smart terminals, infinity really means everything that can
520 * be displayed, or Largest.
521 * On dumb terminals, infinity means every process in the system!
522 * We only really want to do that if it was explicitly specified.
523 * This is always the case when "Default_TOPN != Infinity". But if
524 * topn wasn't explicitly specified and we are on a dumb terminal
525 * and the default is Infinity, then (and only then) we use
526 * "Nominal_TOPN" instead.
528 #if Default_TOPN == Infinity
529 topn = smart_terminal ? Largest :
530 (topn_specified ? Largest : Nominal_TOPN);
536 /* set header display accordingly */
537 display_header(topn > 0);
539 /* determine interactive state */
540 if (interactive == Maybe)
542 interactive = smart_terminal;
545 /* if # of displays not specified, fill it in */
548 displays = smart_terminal ? Infinity : 1;
551 /* hold interrupt signals while setting up the screen and the handlers */
557 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
560 (void) signal(SIGINT, leave);
561 (void) signal(SIGQUIT, leave);
562 (void) signal(SIGTSTP, tstop);
564 (void) signal(SIGWINCH, winch);
571 (void) sigsetmask(old_sigmask);
575 fputs("....", stderr);
576 fflush(stderr); /* why must I do this? */
577 sleep((unsigned)(3 * warnings));
584 * main loop -- repeat while display count is positive or while it
585 * indicates infinity (by being -1)
588 while ((displays == -1) || (displays-- > 0))
593 /* get the current stats */
594 get_system_info(&system_info);
597 compare = compares[order_index];
599 if (displaymode == DISP_CPU)
600 compare = proc_compare;
602 compare = io_compare;
605 /* get the current set of processes */
607 get_process_info(&system_info, &ps, compare);
609 /* display the load averages */
610 (*d_loadave)(system_info.last_pid,
611 system_info.load_avg);
613 /* display the current time */
614 /* this method of getting the time SHOULD be fairly portable */
616 i_uptime(&system_info.boottime, &curr_time);
617 i_timeofday(&curr_time);
619 /* display process state breakdown */
620 (*d_procstates)(system_info.p_total,
621 system_info.procstates);
623 /* display the cpu state percentage breakdown */
624 if (dostates) /* but not the first time */
626 (*d_cpustates)(system_info.cpustates);
630 /* we'll do it next time */
642 /* display memory stats */
643 (*d_memory)(system_info.memory);
645 /* display swap stats */
646 (*d_swap)(system_info.swap);
648 /* handle message area */
651 /* update the header area */
652 (*d_header)(header_text);
656 /* determine number of processes to actually display */
657 /* this number will be the smallest of: active processes,
658 number user requested, number current screen accomodates */
659 active_procs = system_info.P_ACTIVE;
660 if (active_procs > topn)
664 if (active_procs > max_topn)
666 active_procs = max_topn;
669 /* now show the top "n" processes. */
670 for (i = 0; i < active_procs; i++)
672 (*d_process)(i, format_next_process(processes, get_userid,
681 /* do end-screen processing */
684 /* now, flush the output buffer */
685 if (fflush(stdout) != 0)
687 new_message(MT_standout, " Write error on stdout");
693 /* only do the rest if we have more displays to show */
696 /* switch out for new display on smart terminals */
705 d_loadave = u_loadave;
706 d_procstates = u_procstates;
707 d_cpustates = u_cpustates;
710 d_message = u_message;
712 d_process = u_process;
720 (void) signal(SIGALRM, onalrm);
721 (void) alarm((unsigned)delay);
723 /* wait for the rest of it .... */
726 else while (no_command)
728 /* assume valid command unless told otherwise */
731 /* set up arguments for select with timeout */
733 FD_SET(0, &readfds); /* for standard input */
734 timeout.tv_sec = delay;
743 /* move to the lower left */
747 /* default the signal handler action */
748 (void) signal(SIGTSTP, SIG_DFL);
750 /* unblock the signal and send ourselves one */
754 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
756 (void) kill(0, SIGTSTP);
758 /* reset the signal handler */
759 (void) signal(SIGTSTP, tstop);
769 /* reascertain the screen dimensions */
772 /* tell display to resize */
773 max_topn = display_resize();
775 /* reset the signal handler */
776 (void) signal(SIGWINCH, winch);
783 /* wait for either input or the end of the delay period */
784 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
785 if (sel_ret < 0 && errno != EINTR)
792 /* something to read -- clear the message area first */
795 /* now read it and convert to command strchr */
796 /* (use "change" as a temporary to hold strchr) */
797 if (read(0, &ch, 1) != 1)
799 /* read error: either 0 or -1 */
800 new_message(MT_standout, " Read error on stdin");
805 if ((iptr = strchr(command_chars, ch)) == NULL)
807 if (ch != '\r' && ch != '\n')
809 /* illegal command */
810 new_message(MT_standout, " Command not understood");
817 change = iptr - command_chars;
818 if (overstrike && change > CMD_OSLIMIT)
821 new_message(MT_standout,
822 " Command cannot be handled by this terminal");
828 case CMD_redraw: /* redraw screen */
832 case CMD_update: /* merely update display */
833 /* is the load average high? */
834 if (system_info.load_avg[0] > LoadMax)
836 /* yes, go home for visual feedback */
842 case CMD_quit: /* quit */
847 case CMD_help1: /* help */
852 standout("Hit any key to continue: ");
854 (void) read(0, &ch, 1);
857 case CMD_errors: /* show errors */
858 if (error_count() == 0)
860 new_message(MT_standout,
861 " Currently no errors to report.");
870 standout("Hit any key to continue: ");
872 (void) read(0, &ch, 1);
876 case CMD_number1: /* new number */
878 new_message(MT_standout,
879 "Number of processes to show: ");
880 newval = readline(tempbuf1, 8, Yes);
883 if (newval > max_topn)
885 new_message(MT_standout | MT_delayed,
886 " This terminal can only display %d processes.",
893 /* inhibit the header */
896 else if (newval > topn && topn == 0)
898 /* redraw the header */
906 case CMD_delay: /* new seconds delay */
907 new_message(MT_standout, "Seconds to delay: ");
908 if ((i = readline(tempbuf1, 8, Yes)) > -1)
910 if ((delay = i) == 0 && getuid() != 0)
918 case CMD_displays: /* change display count */
919 new_message(MT_standout,
920 "Displays to show (currently %s): ",
921 displays == -1 ? "infinite" :
923 if ((i = readline(tempbuf1, 10, Yes)) > 0)
934 case CMD_kill: /* kill program */
935 new_message(0, "kill ");
936 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
938 if ((errmsg = kill_procs(tempbuf2)) != NULL)
940 new_message(MT_standout, "%s", errmsg);
951 case CMD_renice: /* renice program */
952 new_message(0, "renice ");
953 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
955 if ((errmsg = renice_procs(tempbuf2)) != NULL)
957 new_message(MT_standout, "%s", errmsg);
971 new_message(MT_standout | MT_delayed,
972 " %sisplaying idle processes.",
973 ps.idle ? "D" : "Not d");
978 ps.self = (ps.self == -1) ? getpid() : -1;
979 new_message(MT_standout | MT_delayed,
980 " %sisplaying self.",
981 (ps.self == -1) ? "D" : "Not d");
986 new_message(MT_standout,
987 "Username to show: ");
988 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
990 if (tempbuf2[0] == '+' &&
995 else if ((i = userid(tempbuf2)) == -1)
997 new_message(MT_standout,
998 " %s: unknown user", tempbuf2);
1014 ps.thread = !ps.thread;
1015 new_message(MT_standout | MT_delayed,
1016 "Displaying threads %s",
1017 ps.thread ? "separately" : "as a count");
1018 header_text = format_header(uname_field);
1024 new_message(MT_standout | MT_delayed,
1026 ps.wcpu ? "W" : "");
1027 header_text = format_header(uname_field);
1032 if (++displaymode == DISP_MAX)
1034 header_text = format_header(uname_field);
1035 display_header(Yes);
1036 d_header = i_header;
1040 ps.system = !ps.system;
1043 fmt_flags ^= FMT_SHOWARGS;
1047 new_message(MT_standout,
1049 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1051 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1053 new_message(MT_standout,
1054 " %s: unrecognized sorting order", tempbuf2);
1071 new_message(MT_standout | MT_delayed,
1072 " %sisplaying jail ID.",
1073 ps.jail ? "D" : "Not d");
1074 header_text = format_header(uname_field);
1080 new_message(MT_standout, " BAD CASE IN SWITCH!");
1085 /* flush out stuff that may have been written */
1100 * reset_display() - reset all the display routine pointers so that entire
1101 * screen will get redrawn.
1107 d_loadave = i_loadave;
1108 d_procstates = i_procstates;
1109 d_cpustates = i_cpustates;
1110 d_memory = i_memory;
1112 d_message = i_message;
1113 d_header = i_header;
1114 d_process = i_process;
1121 sigret_t leave() /* exit under normal conditions -- INT handler */
1127 sigret_t tstop(i) /* SIGTSTP handler */
1136 sigret_t winch(i) /* SIGWINCH handler */
1145 void quit(status) /* exit under duress */
1155 sigret_t onalrm() /* SIGALRM handler */
1158 /* this is only used in batch mode to break out of the pause() */