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 */
90 /* routines that don't return int */
98 extern int (*proc_compares[])();
99 extern int (*io_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;
183 struct process_select ps;
185 char *order_name = NULL;
189 /* FD_SET and friends are not present: fake it */
191 #define FD_ZERO(x) (*(x) = 0)
192 #define FD_SET(f, x) (*(x) = 1<<f)
197 static char command_chars[] = "\f qh?en#sdkriIutHmSo";
199 static char command_chars[] = "\f qh?en#sdkriIutHmS";
201 /* these defines enumerate the "strchr"s of the commands in command_chars */
207 #define CMD_OSLIMIT 4 /* terminals with OS can only handle commands */
208 #define CMD_errors 5 /* less than or equal to CMD_OSLIMIT */
209 #define CMD_number1 6
210 #define CMD_number2 7
212 #define CMD_displays 9
214 #define CMD_renice 11
215 #define CMD_idletog 12
216 #define CMD_idletog2 13
218 #define CMD_selftog 15
219 #define CMD_thrtog 16
220 #define CMD_viewtog 17
221 #define CMD_viewsys 18
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 */
256 /* get preset options from the environment */
257 if ((env_top = getenv("TOP")) != NULL)
259 av = preset_argv = argparse(env_top, &preset_argc);
262 /* set the dummy argument to an explanatory message, in case
263 getopt encounters a bad argument */
264 preset_argv[0] = "while processing environment";
267 /* process options */
269 /* if we're done doing the presets, then process the real arguments */
270 if (preset_argc == 0)
275 /* this should keep getopt happy... */
279 while ((i = getopt(ac, av, "SIHbinquvs:d:U:m:o:t")) != EOF)
283 case 'v': /* show version number */
284 fprintf(stderr, "%s: version %s\n",
285 myname, version_string());
289 case 'u': /* toggle uid/username display */
290 do_unames = !do_unames;
293 case 'U': /* display only username's processes */
294 if ((ps.uid = userid(optarg)) == -1)
296 fprintf(stderr, "%s: unknown user\n", optarg);
301 case 'S': /* show system processes */
302 ps.system = !ps.system;
305 case 'I': /* show idle processes */
309 case 'i': /* go interactive regardless */
313 case 'n': /* batch, or non-interactive */
318 case 'd': /* number of displays to show */
319 if ((i = atoiwi(optarg)) == Invalid || i == 0)
322 "%s: warning: display count should be positive -- option ignored\n",
333 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
336 "%s: warning: seconds delay should be positive -- using default\n",
338 delay = Default_DELAY;
343 case 'q': /* be quick about it */
344 /* only allow this if user is really root */
347 /* be very un-nice! */
353 "%s: warning: `-q' option can only be used by root\n",
359 case 'm': /* select display mode */
360 if (strcmp(optarg, "io") == 0) {
361 displaymode = DISP_IO;
362 } else if (strcmp(optarg, "cpu") == 0) {
363 displaymode = DISP_CPU;
366 "%s: warning: `-m' option can only take args "
373 case 'o': /* select sort order */
378 "%s: this platform does not support arbitrary ordering. Sorry.\n",
385 ps.self = (ps.self == -1) ? getpid() : -1;
389 ps.thread = !ps.thread;
395 Usage: %s [-HISbinqut] [-d x] [-s x] [-o field] [-U username] [number]\n",
396 version_string(), myname);
401 /* get count of top processes to display (if any) */
404 if ((topn = atoiwi(av[optind])) == Invalid)
407 "%s: warning: process display count should be non-negative -- using default\n",
411 #if Default_TOPN == Infinity
414 topn_specified = Yes;
419 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
423 /* repeat only if we really did the preset arguments */
426 /* set constants for username/uid display correctly */
429 uname_field = " UID ";
433 /* initialize the kernel memory interface */
434 if (machine_init(&statics) == -1)
440 /* determine sorting order index, if necessary */
441 if (order_name != NULL)
443 if ((order_index = string_index(order_name, statics.order_names)) == -1)
447 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
449 fprintf(stderr, "\tTry one of these:");
450 pp = statics.order_names;
453 fprintf(stderr, " %s", *pp++);
461 #ifdef no_initialization_needed
462 /* initialize the hashing stuff */
469 /* initialize termcap */
470 init_termcap(interactive);
472 /* get the string to use for the process area header */
473 header_text = format_header(uname_field);
475 /* initialize display interface */
476 if ((max_topn = display_init(&statics)) == -1)
478 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
482 /* print warning if user requested more processes than we can display */
486 "%s: warning: this terminal can only display %d processes.\n",
491 /* adjust for topn == Infinity */
492 if (topn == Infinity)
495 * For smart terminals, infinity really means everything that can
496 * be displayed, or Largest.
497 * On dumb terminals, infinity means every process in the system!
498 * We only really want to do that if it was explicitly specified.
499 * This is always the case when "Default_TOPN != Infinity". But if
500 * topn wasn't explicitly specified and we are on a dumb terminal
501 * and the default is Infinity, then (and only then) we use
502 * "Nominal_TOPN" instead.
504 #if Default_TOPN == Infinity
505 topn = smart_terminal ? Largest :
506 (topn_specified ? Largest : Nominal_TOPN);
512 /* set header display accordingly */
513 display_header(topn > 0);
515 /* determine interactive state */
516 if (interactive == Maybe)
518 interactive = smart_terminal;
521 /* if # of displays not specified, fill it in */
524 displays = smart_terminal ? Infinity : 1;
527 /* hold interrupt signals while setting up the screen and the handlers */
533 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
536 (void) signal(SIGINT, leave);
537 (void) signal(SIGQUIT, leave);
538 (void) signal(SIGTSTP, tstop);
540 (void) signal(SIGWINCH, winch);
547 (void) sigsetmask(old_sigmask);
551 fputs("....", stderr);
552 fflush(stderr); /* why must I do this? */
553 sleep((unsigned)(3 * warnings));
560 * main loop -- repeat while display count is positive or while it
561 * indicates infinity (by being -1)
564 while ((displays == -1) || (displays-- > 0))
569 /* get the current stats */
570 get_system_info(&system_info);
573 if (displaymode == DISP_CPU)
574 compare = proc_compares[order_index];
576 compare = io_compares[order_index];
578 if (displaymode == DISP_CPU)
579 compare = proc_compare;
581 compare = io_compare;
584 /* get the current set of processes */
586 get_process_info(&system_info, &ps, compare);
588 /* display the load averages */
589 (*d_loadave)(system_info.last_pid,
590 system_info.load_avg);
592 /* display the current time */
593 /* this method of getting the time SHOULD be fairly portable */
595 i_uptime(&system_info.boottime, &curr_time);
596 i_timeofday(&curr_time);
598 /* display process state breakdown */
599 (*d_procstates)(system_info.p_total,
600 system_info.procstates);
602 /* display the cpu state percentage breakdown */
603 if (dostates) /* but not the first time */
605 (*d_cpustates)(system_info.cpustates);
609 /* we'll do it next time */
621 /* display memory stats */
622 (*d_memory)(system_info.memory);
624 /* display swap stats */
625 (*d_swap)(system_info.swap);
627 /* handle message area */
630 /* update the header area */
631 (*d_header)(header_text);
635 /* determine number of processes to actually display */
636 /* this number will be the smallest of: active processes,
637 number user requested, number current screen accomodates */
638 active_procs = system_info.P_ACTIVE;
639 if (active_procs > topn)
643 if (active_procs > max_topn)
645 active_procs = max_topn;
648 /* now show the top "n" processes. */
649 for (i = 0; i < active_procs; i++)
651 (*d_process)(i, format_next_process(processes, get_userid));
659 /* do end-screen processing */
662 /* now, flush the output buffer */
663 if (fflush(stdout) != 0)
665 new_message(MT_standout, " Write error on stdout");
671 /* only do the rest if we have more displays to show */
674 /* switch out for new display on smart terminals */
683 d_loadave = u_loadave;
684 d_procstates = u_procstates;
685 d_cpustates = u_cpustates;
688 d_message = u_message;
690 d_process = u_process;
698 (void) signal(SIGALRM, onalrm);
699 (void) alarm((unsigned)delay);
701 /* wait for the rest of it .... */
704 else while (no_command)
706 /* assume valid command unless told otherwise */
709 /* set up arguments for select with timeout */
711 FD_SET(0, &readfds); /* for standard input */
712 timeout.tv_sec = delay;
721 /* move to the lower left */
725 /* default the signal handler action */
726 (void) signal(SIGTSTP, SIG_DFL);
728 /* unblock the signal and send ourselves one */
732 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
734 (void) kill(0, SIGTSTP);
736 /* reset the signal handler */
737 (void) signal(SIGTSTP, tstop);
747 /* reascertain the screen dimensions */
750 /* tell display to resize */
751 max_topn = display_resize();
753 /* reset the signal handler */
754 (void) signal(SIGWINCH, winch);
761 /* wait for either input or the end of the delay period */
762 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
763 if (sel_ret < 0 && errno != EINTR)
770 /* something to read -- clear the message area first */
773 /* now read it and convert to command strchr */
774 /* (use "change" as a temporary to hold strchr) */
775 if (read(0, &ch, 1) != 1)
777 /* read error: either 0 or -1 */
778 new_message(MT_standout, " Read error on stdin");
783 if ((iptr = strchr(command_chars, ch)) == NULL)
785 if (ch != '\r' && ch != '\n')
787 /* illegal command */
788 new_message(MT_standout, " Command not understood");
795 change = iptr - command_chars;
796 if (overstrike && change > CMD_OSLIMIT)
799 new_message(MT_standout,
800 " Command cannot be handled by this terminal");
806 case CMD_redraw: /* redraw screen */
810 case CMD_update: /* merely update display */
811 /* is the load average high? */
812 if (system_info.load_avg[0] > LoadMax)
814 /* yes, go home for visual feedback */
820 case CMD_quit: /* quit */
825 case CMD_help1: /* help */
830 standout("Hit any key to continue: ");
832 (void) read(0, &ch, 1);
835 case CMD_errors: /* show errors */
836 if (error_count() == 0)
838 new_message(MT_standout,
839 " Currently no errors to report.");
848 standout("Hit any key to continue: ");
850 (void) read(0, &ch, 1);
854 case CMD_number1: /* new number */
856 new_message(MT_standout,
857 "Number of processes to show: ");
858 newval = readline(tempbuf1, 8, Yes);
861 if (newval > max_topn)
863 new_message(MT_standout | MT_delayed,
864 " This terminal can only display %d processes.",
871 /* inhibit the header */
874 else if (newval > topn && topn == 0)
876 /* redraw the header */
884 case CMD_delay: /* new seconds delay */
885 new_message(MT_standout, "Seconds to delay: ");
886 if ((i = readline(tempbuf1, 8, Yes)) > -1)
888 if ((delay = i) == 0 && getuid() != 0)
896 case CMD_displays: /* change display count */
897 new_message(MT_standout,
898 "Displays to show (currently %s): ",
899 displays == -1 ? "infinite" :
901 if ((i = readline(tempbuf1, 10, Yes)) > 0)
912 case CMD_kill: /* kill program */
913 new_message(0, "kill ");
914 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
916 if ((errmsg = kill_procs(tempbuf2)) != NULL)
918 new_message(MT_standout, "%s", errmsg);
929 case CMD_renice: /* renice program */
930 new_message(0, "renice ");
931 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
933 if ((errmsg = renice_procs(tempbuf2)) != NULL)
935 new_message(MT_standout, "%s", errmsg);
949 new_message(MT_standout | MT_delayed,
950 " %sisplaying idle processes.",
951 ps.idle ? "D" : "Not d");
956 ps.self = (ps.self == -1) ? getpid() : -1;
957 new_message(MT_standout | MT_delayed,
958 " %sisplaying self.",
959 (ps.self == -1) ? "D" : "Not d");
964 new_message(MT_standout,
965 "Username to show: ");
966 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
968 if (tempbuf2[0] == '+' &&
973 else if ((i = userid(tempbuf2)) == -1)
975 new_message(MT_standout,
976 " %s: unknown user", tempbuf2);
992 ps.thread = !ps.thread;
993 new_message(MT_standout | MT_delayed,
994 " %sisplaying threads.",
995 ps.thread ? "D" : "Not d");
999 if (++displaymode == DISP_MAX)
1001 header_text = format_header(uname_field);
1002 display_header(Yes);
1003 d_header = i_header;
1007 ps.system = !ps.system;
1011 new_message(MT_standout,
1013 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1015 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1017 new_message(MT_standout,
1018 " %s: unrecognized sorting order", tempbuf2);
1035 new_message(MT_standout, " BAD CASE IN SWITCH!");
1040 /* flush out stuff that may have been written */
1055 * reset_display() - reset all the display routine pointers so that entire
1056 * screen will get redrawn.
1062 d_loadave = i_loadave;
1063 d_procstates = i_procstates;
1064 d_cpustates = i_cpustates;
1065 d_memory = i_memory;
1067 d_message = i_message;
1068 d_header = i_header;
1069 d_process = i_process;
1076 sigret_t leave() /* exit under normal conditions -- INT handler */
1082 sigret_t tstop(i) /* SIGTSTP handler */
1091 sigret_t winch(i) /* SIGWINCH handler */
1100 void quit(status) /* exit under duress */
1110 sigret_t onalrm() /* SIGALRM handler */
1113 /* this is only used in batch mode to break out of the pause() */