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 (*compares[])();
100 extern int proc_compare();
101 extern int io_compare();
105 caddr_t get_process_info();
107 /* different routines for displaying the user's identification */
108 /* (values assigned to get_userid) */
112 /* display routines that need to be predeclared */
130 /* pointers to display routines */
131 int (*d_loadave)() = i_loadave;
132 int (*d_procstates)() = i_procstates;
133 int (*d_cpustates)() = i_cpustates;
134 int (*d_memory)() = i_memory;
135 int (*d_swap)() = i_swap;
136 int (*d_message)() = i_message;
137 int (*d_header)() = i_header;
138 int (*d_process)() = i_process;
148 register int active_procs;
151 struct system_info system_info;
152 struct statics statics;
155 static char tempbuf1[50];
156 static char tempbuf2[50];
157 int old_sigmask; /* only used for BSD-style signals */
158 int topn = Default_TOPN;
159 int delay = Default_DELAY;
160 int displays = 0; /* indicates unspecified */
163 char *(*get_userid)() = username;
164 char *uname_field = "USERNAME";
172 char do_unames = Yes;
173 char interactive = Maybe;
175 #if Default_TOPN == Infinity
176 char topn_specified = No;
181 struct timeval timeout;
182 struct process_select ps;
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#sdkriIutHmSo";
198 static char command_chars[] = "\f qh?en#sdkriIutHmS";
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
225 /* set the buffer for stdout */
228 debug = fopen("debug.run", "w");
229 setbuffer(stdout, NULL, 0);
231 setbuffer(stdout, stdoutbuf, Buffersize);
237 if ((myname = strrchr(argv[0], '/')) == 0)
247 /* initialize some selection options */
255 /* get preset options from the environment */
256 if ((env_top = getenv("TOP")) != NULL)
258 av = preset_argv = argparse(env_top, &preset_argc);
261 /* set the dummy argument to an explanatory message, in case
262 getopt encounters a bad argument */
263 preset_argv[0] = "while processing environment";
266 /* process options */
268 /* if we're done doing the presets, then process the real arguments */
269 if (preset_argc == 0)
274 /* this should keep getopt happy... */
278 while ((i = getopt(ac, av, "SIHbinquvs:d:U:m:o:t")) != EOF)
282 case 'v': /* show version number */
283 fprintf(stderr, "%s: version %s\n",
284 myname, version_string());
288 case 'u': /* toggle uid/username display */
289 do_unames = !do_unames;
292 case 'U': /* display only username's processes */
293 if ((ps.uid = userid(optarg)) == -1)
295 fprintf(stderr, "%s: unknown user\n", optarg);
300 case 'S': /* show system processes */
301 ps.system = !ps.system;
304 case 'I': /* show idle processes */
308 case 'i': /* go interactive regardless */
312 case 'n': /* batch, or non-interactive */
317 case 'd': /* number of displays to show */
318 if ((i = atoiwi(optarg)) == Invalid || i == 0)
321 "%s: warning: display count should be positive -- option ignored\n",
332 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
335 "%s: warning: seconds delay should be positive -- using default\n",
337 delay = Default_DELAY;
342 case 'q': /* be quick about it */
343 /* only allow this if user is really root */
346 /* be very un-nice! */
352 "%s: warning: `-q' option can only be used by root\n",
358 case 'm': /* select display mode */
359 if (strcmp(optarg, "io") == 0) {
360 displaymode = DISP_IO;
361 } else if (strcmp(optarg, "cpu") == 0) {
362 displaymode = DISP_CPU;
365 "%s: warning: `-m' option can only take args "
372 case 'o': /* select sort order */
377 "%s: this platform does not support arbitrary ordering. Sorry.\n",
384 ps.self = (ps.self == -1) ? getpid() : -1;
388 ps.thread = !ps.thread;
394 Usage: %s [-HISbinqut] [-d x] [-s x] [-o field] [-U username] [number]\n",
395 version_string(), myname);
400 /* get count of top processes to display (if any) */
403 if ((topn = atoiwi(av[optind])) == Invalid)
406 "%s: warning: process display count should be non-negative -- using default\n",
410 #if Default_TOPN == Infinity
413 topn_specified = Yes;
418 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
422 /* repeat only if we really did the preset arguments */
425 /* set constants for username/uid display correctly */
428 uname_field = " UID ";
432 /* initialize the kernel memory interface */
433 if (machine_init(&statics) == -1)
439 /* determine sorting order index, if necessary */
440 if (order_name != NULL)
442 if ((order_index = string_index(order_name, statics.order_names)) == -1)
446 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
448 fprintf(stderr, "\tTry one of these:");
449 pp = statics.order_names;
452 fprintf(stderr, " %s", *pp++);
460 #ifdef no_initialization_needed
461 /* initialize the hashing stuff */
468 /* initialize termcap */
469 init_termcap(interactive);
471 /* get the string to use for the process area header */
472 header_text = format_header(uname_field);
474 /* initialize display interface */
475 if ((max_topn = display_init(&statics)) == -1)
477 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
481 /* print warning if user requested more processes than we can display */
485 "%s: warning: this terminal can only display %d processes.\n",
490 /* adjust for topn == Infinity */
491 if (topn == Infinity)
494 * For smart terminals, infinity really means everything that can
495 * be displayed, or Largest.
496 * On dumb terminals, infinity means every process in the system!
497 * We only really want to do that if it was explicitly specified.
498 * This is always the case when "Default_TOPN != Infinity". But if
499 * topn wasn't explicitly specified and we are on a dumb terminal
500 * and the default is Infinity, then (and only then) we use
501 * "Nominal_TOPN" instead.
503 #if Default_TOPN == Infinity
504 topn = smart_terminal ? Largest :
505 (topn_specified ? Largest : Nominal_TOPN);
511 /* set header display accordingly */
512 display_header(topn > 0);
514 /* determine interactive state */
515 if (interactive == Maybe)
517 interactive = smart_terminal;
520 /* if # of displays not specified, fill it in */
523 displays = smart_terminal ? Infinity : 1;
526 /* hold interrupt signals while setting up the screen and the handlers */
532 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
535 (void) signal(SIGINT, leave);
536 (void) signal(SIGQUIT, leave);
537 (void) signal(SIGTSTP, tstop);
539 (void) signal(SIGWINCH, winch);
546 (void) sigsetmask(old_sigmask);
550 fputs("....", stderr);
551 fflush(stderr); /* why must I do this? */
552 sleep((unsigned)(3 * warnings));
559 * main loop -- repeat while display count is positive or while it
560 * indicates infinity (by being -1)
563 while ((displays == -1) || (displays-- > 0))
568 /* get the current stats */
569 get_system_info(&system_info);
572 compare = compares[order_index];
574 if (displaymode == DISP_CPU)
575 compare = proc_compare;
577 compare = io_compare;
580 /* get the current set of processes */
582 get_process_info(&system_info, &ps, compare);
584 /* display the load averages */
585 (*d_loadave)(system_info.last_pid,
586 system_info.load_avg);
588 /* display the current time */
589 /* this method of getting the time SHOULD be fairly portable */
591 i_uptime(&system_info.boottime, &curr_time);
592 i_timeofday(&curr_time);
594 /* display process state breakdown */
595 (*d_procstates)(system_info.p_total,
596 system_info.procstates);
598 /* display the cpu state percentage breakdown */
599 if (dostates) /* but not the first time */
601 (*d_cpustates)(system_info.cpustates);
605 /* we'll do it next time */
617 /* display memory stats */
618 (*d_memory)(system_info.memory);
620 /* display swap stats */
621 (*d_swap)(system_info.swap);
623 /* handle message area */
626 /* update the header area */
627 (*d_header)(header_text);
631 /* determine number of processes to actually display */
632 /* this number will be the smallest of: active processes,
633 number user requested, number current screen accomodates */
634 active_procs = system_info.P_ACTIVE;
635 if (active_procs > topn)
639 if (active_procs > max_topn)
641 active_procs = max_topn;
644 /* now show the top "n" processes. */
645 for (i = 0; i < active_procs; i++)
647 (*d_process)(i, format_next_process(processes, get_userid));
655 /* do end-screen processing */
658 /* now, flush the output buffer */
659 if (fflush(stdout) != 0)
661 new_message(MT_standout, " Write error on stdout");
667 /* only do the rest if we have more displays to show */
670 /* switch out for new display on smart terminals */
679 d_loadave = u_loadave;
680 d_procstates = u_procstates;
681 d_cpustates = u_cpustates;
684 d_message = u_message;
686 d_process = u_process;
694 (void) signal(SIGALRM, onalrm);
695 (void) alarm((unsigned)delay);
697 /* wait for the rest of it .... */
700 else while (no_command)
702 /* assume valid command unless told otherwise */
705 /* set up arguments for select with timeout */
707 FD_SET(0, &readfds); /* for standard input */
708 timeout.tv_sec = delay;
717 /* move to the lower left */
721 /* default the signal handler action */
722 (void) signal(SIGTSTP, SIG_DFL);
724 /* unblock the signal and send ourselves one */
728 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
730 (void) kill(0, SIGTSTP);
732 /* reset the signal handler */
733 (void) signal(SIGTSTP, tstop);
743 /* reascertain the screen dimensions */
746 /* tell display to resize */
747 max_topn = display_resize();
749 /* reset the signal handler */
750 (void) signal(SIGWINCH, winch);
757 /* wait for either input or the end of the delay period */
758 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
759 if (sel_ret < 0 && errno != EINTR)
766 /* something to read -- clear the message area first */
769 /* now read it and convert to command strchr */
770 /* (use "change" as a temporary to hold strchr) */
771 if (read(0, &ch, 1) != 1)
773 /* read error: either 0 or -1 */
774 new_message(MT_standout, " Read error on stdin");
779 if ((iptr = strchr(command_chars, ch)) == NULL)
781 if (ch != '\r' && ch != '\n')
783 /* illegal command */
784 new_message(MT_standout, " Command not understood");
791 change = iptr - command_chars;
792 if (overstrike && change > CMD_OSLIMIT)
795 new_message(MT_standout,
796 " Command cannot be handled by this terminal");
802 case CMD_redraw: /* redraw screen */
806 case CMD_update: /* merely update display */
807 /* is the load average high? */
808 if (system_info.load_avg[0] > LoadMax)
810 /* yes, go home for visual feedback */
816 case CMD_quit: /* quit */
821 case CMD_help1: /* help */
826 standout("Hit any key to continue: ");
828 (void) read(0, &ch, 1);
831 case CMD_errors: /* show errors */
832 if (error_count() == 0)
834 new_message(MT_standout,
835 " Currently no errors to report.");
844 standout("Hit any key to continue: ");
846 (void) read(0, &ch, 1);
850 case CMD_number1: /* new number */
852 new_message(MT_standout,
853 "Number of processes to show: ");
854 newval = readline(tempbuf1, 8, Yes);
857 if (newval > max_topn)
859 new_message(MT_standout | MT_delayed,
860 " This terminal can only display %d processes.",
867 /* inhibit the header */
870 else if (newval > topn && topn == 0)
872 /* redraw the header */
880 case CMD_delay: /* new seconds delay */
881 new_message(MT_standout, "Seconds to delay: ");
882 if ((i = readline(tempbuf1, 8, Yes)) > -1)
884 if ((delay = i) == 0 && getuid() != 0)
892 case CMD_displays: /* change display count */
893 new_message(MT_standout,
894 "Displays to show (currently %s): ",
895 displays == -1 ? "infinite" :
897 if ((i = readline(tempbuf1, 10, Yes)) > 0)
908 case CMD_kill: /* kill program */
909 new_message(0, "kill ");
910 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
912 if ((errmsg = kill_procs(tempbuf2)) != NULL)
914 new_message(MT_standout, "%s", errmsg);
925 case CMD_renice: /* renice program */
926 new_message(0, "renice ");
927 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
929 if ((errmsg = renice_procs(tempbuf2)) != NULL)
931 new_message(MT_standout, "%s", errmsg);
945 new_message(MT_standout | MT_delayed,
946 " %sisplaying idle processes.",
947 ps.idle ? "D" : "Not d");
952 ps.self = (ps.self == -1) ? getpid() : -1;
953 new_message(MT_standout | MT_delayed,
954 " %sisplaying self.",
955 (ps.self == -1) ? "D" : "Not d");
960 new_message(MT_standout,
961 "Username to show: ");
962 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
964 if (tempbuf2[0] == '+' &&
969 else if ((i = userid(tempbuf2)) == -1)
971 new_message(MT_standout,
972 " %s: unknown user", tempbuf2);
988 ps.thread = !ps.thread;
989 new_message(MT_standout | MT_delayed,
990 " %sisplaying threads.",
991 ps.thread ? "D" : "Not d");
995 if (++displaymode == DISP_MAX)
997 header_text = format_header(uname_field);
1003 ps.system = !ps.system;
1007 new_message(MT_standout,
1009 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1011 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1013 new_message(MT_standout,
1014 " %s: unrecognized sorting order", tempbuf2);
1031 new_message(MT_standout, " BAD CASE IN SWITCH!");
1036 /* flush out stuff that may have been written */
1051 * reset_display() - reset all the display routine pointers so that entire
1052 * screen will get redrawn.
1058 d_loadave = i_loadave;
1059 d_procstates = i_procstates;
1060 d_cpustates = i_cpustates;
1061 d_memory = i_memory;
1063 d_message = i_message;
1064 d_header = i_header;
1065 d_process = i_process;
1072 sigret_t leave() /* exit under normal conditions -- INT handler */
1078 sigret_t tstop(i) /* SIGTSTP handler */
1087 sigret_t winch(i) /* SIGWINCH handler */
1096 void quit(status) /* exit under duress */
1106 sigret_t onalrm() /* SIGALRM handler */
1109 /* this is only used in batch mode to break out of the pause() */