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 /* signal handling routines */
76 volatile sig_atomic_t leaveflag;
77 volatile sig_atomic_t tstopflag;
78 volatile sig_atomic_t winchflag;
80 /* internal routines */
83 /* values which need to be accessed by signal handlers */
84 static int max_topn; /* maximum displayable processes */
86 /* miscellaneous things */
87 struct process_select ps;
91 /* routines that don't return int */
99 extern int (*compares[])();
101 extern int proc_compare();
102 extern int io_compare();
106 caddr_t get_process_info();
108 /* different routines for displaying the user's identification */
109 /* (values assigned to get_userid) */
113 /* display routines that need to be predeclared */
131 /* pointers to display routines */
132 int (*d_loadave)() = i_loadave;
133 int (*d_procstates)() = i_procstates;
134 int (*d_cpustates)() = i_cpustates;
135 int (*d_memory)() = i_memory;
136 int (*d_swap)() = i_swap;
137 int (*d_message)() = i_message;
138 int (*d_header)() = i_header;
139 int (*d_process)() = i_process;
149 register int active_procs;
152 struct system_info system_info;
153 struct statics statics;
156 static char tempbuf1[50];
157 static char tempbuf2[50];
158 int old_sigmask; /* only used for BSD-style signals */
159 int topn = Default_TOPN;
160 int delay = Default_DELAY;
161 int displays = 0; /* indicates unspecified */
164 char *(*get_userid)() = username;
165 char *uname_field = "USERNAME";
173 char do_unames = Yes;
174 char interactive = Maybe;
176 #if Default_TOPN == Infinity
177 char topn_specified = No;
182 struct timeval timeout;
184 char *order_name = NULL;
188 /* FD_SET and friends are not present: fake it */
190 #define FD_ZERO(x) (*(x) = 0)
191 #define FD_SET(f, x) (*(x) = 1<<f)
196 static char command_chars[] = "\f qh?en#sdkriIutHmSCo";
198 static char command_chars[] = "\f qh?en#sdkriIutHmSC";
200 /* these defines enumerate the "strchr"s of the commands in command_chars */
206 #define CMD_OSLIMIT 4 /* terminals with OS can only handle commands */
207 #define CMD_errors 5 /* less than or equal to CMD_OSLIMIT */
208 #define CMD_number1 6
209 #define CMD_number2 7
211 #define CMD_displays 9
213 #define CMD_renice 11
214 #define CMD_idletog 12
215 #define CMD_idletog2 13
217 #define CMD_selftog 15
218 #define CMD_thrtog 16
219 #define CMD_viewtog 17
220 #define CMD_viewsys 18
221 #define CMD_wcputog 19
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 */
257 /* get preset options from the environment */
258 if ((env_top = getenv("TOP")) != NULL)
260 av = preset_argv = argparse(env_top, &preset_argc);
263 /* set the dummy argument to an explanatory message, in case
264 getopt encounters a bad argument */
265 preset_argv[0] = "while processing environment";
268 /* process options */
270 /* if we're done doing the presets, then process the real arguments */
271 if (preset_argc == 0)
276 /* this should keep getopt happy... */
280 while ((i = getopt(ac, av, "CSIHbinquvs:d:U:m:o:t")) != EOF)
284 case 'v': /* show version number */
285 fprintf(stderr, "%s: version %s\n",
286 myname, version_string());
290 case 'u': /* toggle uid/username display */
291 do_unames = !do_unames;
294 case 'U': /* display only username's processes */
295 if ((ps.uid = userid(optarg)) == -1)
297 fprintf(stderr, "%s: unknown user\n", optarg);
302 case 'S': /* show system processes */
303 ps.system = !ps.system;
306 case 'I': /* show idle processes */
310 case 'i': /* go interactive regardless */
314 case 'n': /* batch, or non-interactive */
319 case 'd': /* number of displays to show */
320 if ((i = atoiwi(optarg)) == Invalid || i == 0)
323 "%s: warning: display count should be positive -- option ignored\n",
334 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
337 "%s: warning: seconds delay should be positive -- using default\n",
339 delay = Default_DELAY;
344 case 'q': /* be quick about it */
345 /* only allow this if user is really root */
348 /* be very un-nice! */
354 "%s: warning: `-q' option can only be used by root\n",
360 case 'm': /* select display mode */
361 if (strcmp(optarg, "io") == 0) {
362 displaymode = DISP_IO;
363 } else if (strcmp(optarg, "cpu") == 0) {
364 displaymode = DISP_CPU;
367 "%s: warning: `-m' option can only take args "
374 case 'o': /* select sort order */
379 "%s: this platform does not support arbitrary ordering. Sorry.\n",
386 ps.self = (ps.self == -1) ? getpid() : -1;
394 ps.thread = !ps.thread;
400 Usage: %s [-CHISbinqut] [-d x] [-s x] [-o field] [-U username] [number]\n",
401 version_string(), myname);
406 /* get count of top processes to display (if any) */
409 if ((topn = atoiwi(av[optind])) == Invalid)
412 "%s: warning: process display count should be non-negative -- using default\n",
416 #if Default_TOPN == Infinity
419 topn_specified = Yes;
424 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
428 /* repeat only if we really did the preset arguments */
431 /* set constants for username/uid display correctly */
434 uname_field = " UID ";
438 /* initialize the kernel memory interface */
439 if (machine_init(&statics) == -1)
445 /* determine sorting order index, if necessary */
446 if (order_name != NULL)
448 if ((order_index = string_index(order_name, statics.order_names)) == -1)
452 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
454 fprintf(stderr, "\tTry one of these:");
455 pp = statics.order_names;
458 fprintf(stderr, " %s", *pp++);
466 #ifdef no_initialization_needed
467 /* initialize the hashing stuff */
474 /* initialize termcap */
475 init_termcap(interactive);
477 /* get the string to use for the process area header */
478 header_text = format_header(uname_field);
480 /* initialize display interface */
481 if ((max_topn = display_init(&statics)) == -1)
483 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
487 /* print warning if user requested more processes than we can display */
491 "%s: warning: this terminal can only display %d processes.\n",
496 /* adjust for topn == Infinity */
497 if (topn == Infinity)
500 * For smart terminals, infinity really means everything that can
501 * be displayed, or Largest.
502 * On dumb terminals, infinity means every process in the system!
503 * We only really want to do that if it was explicitly specified.
504 * This is always the case when "Default_TOPN != Infinity". But if
505 * topn wasn't explicitly specified and we are on a dumb terminal
506 * and the default is Infinity, then (and only then) we use
507 * "Nominal_TOPN" instead.
509 #if Default_TOPN == Infinity
510 topn = smart_terminal ? Largest :
511 (topn_specified ? Largest : Nominal_TOPN);
517 /* set header display accordingly */
518 display_header(topn > 0);
520 /* determine interactive state */
521 if (interactive == Maybe)
523 interactive = smart_terminal;
526 /* if # of displays not specified, fill it in */
529 displays = smart_terminal ? Infinity : 1;
532 /* hold interrupt signals while setting up the screen and the handlers */
538 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
541 (void) signal(SIGINT, leave);
542 (void) signal(SIGQUIT, leave);
543 (void) signal(SIGTSTP, tstop);
545 (void) signal(SIGWINCH, winch);
552 (void) sigsetmask(old_sigmask);
556 fputs("....", stderr);
557 fflush(stderr); /* why must I do this? */
558 sleep((unsigned)(3 * warnings));
565 * main loop -- repeat while display count is positive or while it
566 * indicates infinity (by being -1)
569 while ((displays == -1) || (displays-- > 0))
574 /* get the current stats */
575 get_system_info(&system_info);
578 compare = compares[order_index];
580 if (displaymode == DISP_CPU)
581 compare = proc_compare;
583 compare = io_compare;
586 /* get the current set of processes */
588 get_process_info(&system_info, &ps, compare);
590 /* display the load averages */
591 (*d_loadave)(system_info.last_pid,
592 system_info.load_avg);
594 /* display the current time */
595 /* this method of getting the time SHOULD be fairly portable */
597 i_uptime(&system_info.boottime, &curr_time);
598 i_timeofday(&curr_time);
600 /* display process state breakdown */
601 (*d_procstates)(system_info.p_total,
602 system_info.procstates);
604 /* display the cpu state percentage breakdown */
605 if (dostates) /* but not the first time */
607 (*d_cpustates)(system_info.cpustates);
611 /* we'll do it next time */
623 /* display memory stats */
624 (*d_memory)(system_info.memory);
626 /* display swap stats */
627 (*d_swap)(system_info.swap);
629 /* handle message area */
632 /* update the header area */
633 (*d_header)(header_text);
637 /* determine number of processes to actually display */
638 /* this number will be the smallest of: active processes,
639 number user requested, number current screen accomodates */
640 active_procs = system_info.P_ACTIVE;
641 if (active_procs > topn)
645 if (active_procs > max_topn)
647 active_procs = max_topn;
650 /* now show the top "n" processes. */
651 for (i = 0; i < active_procs; i++)
653 (*d_process)(i, format_next_process(processes, get_userid));
661 /* do end-screen processing */
664 /* now, flush the output buffer */
665 if (fflush(stdout) != 0)
667 new_message(MT_standout, " Write error on stdout");
673 /* only do the rest if we have more displays to show */
676 /* switch out for new display on smart terminals */
685 d_loadave = u_loadave;
686 d_procstates = u_procstates;
687 d_cpustates = u_cpustates;
690 d_message = u_message;
692 d_process = u_process;
700 (void) signal(SIGALRM, onalrm);
701 (void) alarm((unsigned)delay);
703 /* wait for the rest of it .... */
706 else while (no_command)
708 /* assume valid command unless told otherwise */
711 /* set up arguments for select with timeout */
713 FD_SET(0, &readfds); /* for standard input */
714 timeout.tv_sec = delay;
723 /* move to the lower left */
727 /* default the signal handler action */
728 (void) signal(SIGTSTP, SIG_DFL);
730 /* unblock the signal and send ourselves one */
734 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
736 (void) kill(0, SIGTSTP);
738 /* reset the signal handler */
739 (void) signal(SIGTSTP, tstop);
749 /* reascertain the screen dimensions */
752 /* tell display to resize */
753 max_topn = display_resize();
755 /* reset the signal handler */
756 (void) signal(SIGWINCH, winch);
763 /* wait for either input or the end of the delay period */
764 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
765 if (sel_ret < 0 && errno != EINTR)
772 /* something to read -- clear the message area first */
775 /* now read it and convert to command strchr */
776 /* (use "change" as a temporary to hold strchr) */
777 if (read(0, &ch, 1) != 1)
779 /* read error: either 0 or -1 */
780 new_message(MT_standout, " Read error on stdin");
785 if ((iptr = strchr(command_chars, ch)) == NULL)
787 if (ch != '\r' && ch != '\n')
789 /* illegal command */
790 new_message(MT_standout, " Command not understood");
797 change = iptr - command_chars;
798 if (overstrike && change > CMD_OSLIMIT)
801 new_message(MT_standout,
802 " Command cannot be handled by this terminal");
808 case CMD_redraw: /* redraw screen */
812 case CMD_update: /* merely update display */
813 /* is the load average high? */
814 if (system_info.load_avg[0] > LoadMax)
816 /* yes, go home for visual feedback */
822 case CMD_quit: /* quit */
827 case CMD_help1: /* help */
832 standout("Hit any key to continue: ");
834 (void) read(0, &ch, 1);
837 case CMD_errors: /* show errors */
838 if (error_count() == 0)
840 new_message(MT_standout,
841 " Currently no errors to report.");
850 standout("Hit any key to continue: ");
852 (void) read(0, &ch, 1);
856 case CMD_number1: /* new number */
858 new_message(MT_standout,
859 "Number of processes to show: ");
860 newval = readline(tempbuf1, 8, Yes);
863 if (newval > max_topn)
865 new_message(MT_standout | MT_delayed,
866 " This terminal can only display %d processes.",
873 /* inhibit the header */
876 else if (newval > topn && topn == 0)
878 /* redraw the header */
886 case CMD_delay: /* new seconds delay */
887 new_message(MT_standout, "Seconds to delay: ");
888 if ((i = readline(tempbuf1, 8, Yes)) > -1)
890 if ((delay = i) == 0 && getuid() != 0)
898 case CMD_displays: /* change display count */
899 new_message(MT_standout,
900 "Displays to show (currently %s): ",
901 displays == -1 ? "infinite" :
903 if ((i = readline(tempbuf1, 10, Yes)) > 0)
914 case CMD_kill: /* kill program */
915 new_message(0, "kill ");
916 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
918 if ((errmsg = kill_procs(tempbuf2)) != NULL)
920 new_message(MT_standout, "%s", errmsg);
931 case CMD_renice: /* renice program */
932 new_message(0, "renice ");
933 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
935 if ((errmsg = renice_procs(tempbuf2)) != NULL)
937 new_message(MT_standout, "%s", errmsg);
951 new_message(MT_standout | MT_delayed,
952 " %sisplaying idle processes.",
953 ps.idle ? "D" : "Not d");
958 ps.self = (ps.self == -1) ? getpid() : -1;
959 new_message(MT_standout | MT_delayed,
960 " %sisplaying self.",
961 (ps.self == -1) ? "D" : "Not d");
966 new_message(MT_standout,
967 "Username to show: ");
968 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
970 if (tempbuf2[0] == '+' &&
975 else if ((i = userid(tempbuf2)) == -1)
977 new_message(MT_standout,
978 " %s: unknown user", tempbuf2);
994 ps.thread = !ps.thread;
995 new_message(MT_standout | MT_delayed,
996 "Displaying threads %s",
997 ps.thread ? "separately" : "as a count");
998 header_text = format_header(uname_field);
1004 new_message(MT_standout | MT_delayed,
1006 ps.wcpu ? "W" : "");
1007 header_text = format_header(uname_field);
1012 if (++displaymode == DISP_MAX)
1014 header_text = format_header(uname_field);
1015 display_header(Yes);
1016 d_header = i_header;
1020 ps.system = !ps.system;
1024 new_message(MT_standout,
1026 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1028 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1030 new_message(MT_standout,
1031 " %s: unrecognized sorting order", tempbuf2);
1048 new_message(MT_standout, " BAD CASE IN SWITCH!");
1053 /* flush out stuff that may have been written */
1068 * reset_display() - reset all the display routine pointers so that entire
1069 * screen will get redrawn.
1075 d_loadave = i_loadave;
1076 d_procstates = i_procstates;
1077 d_cpustates = i_cpustates;
1078 d_memory = i_memory;
1080 d_message = i_message;
1081 d_header = i_header;
1082 d_process = i_process;
1089 sigret_t leave() /* exit under normal conditions -- INT handler */
1095 sigret_t tstop(i) /* SIGTSTP handler */
1104 sigret_t winch(i) /* SIGWINCH handler */
1113 void quit(status) /* exit under duress */
1123 sigret_t onalrm() /* SIGALRM handler */
1126 /* this is only used in batch mode to break out of the pause() */