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[])();
100 extern int proc_compare();
104 caddr_t get_process_info();
106 /* different routines for displaying the user's identification */
107 /* (values assigned to get_userid) */
111 /* display routines that need to be predeclared */
129 /* pointers to display routines */
130 int (*d_loadave)() = i_loadave;
131 int (*d_procstates)() = i_procstates;
132 int (*d_cpustates)() = i_cpustates;
133 int (*d_memory)() = i_memory;
134 int (*d_swap)() = i_swap;
135 int (*d_message)() = i_message;
136 int (*d_header)() = i_header;
137 int (*d_process)() = i_process;
147 register int active_procs;
150 struct system_info system_info;
151 struct statics statics;
154 static char tempbuf1[50];
155 static char tempbuf2[50];
156 int old_sigmask; /* only used for BSD-style signals */
157 int topn = Default_TOPN;
158 int delay = Default_DELAY;
159 int displays = 0; /* indicates unspecified */
162 char *(*get_userid)() = username;
163 char *uname_field = "USERNAME";
171 char do_unames = Yes;
172 char interactive = Maybe;
174 #if Default_TOPN == Infinity
175 char topn_specified = No;
180 struct timeval timeout;
181 struct process_select ps;
183 char *order_name = NULL;
187 /* FD_SET and friends are not present: fake it */
189 #define FD_ZERO(x) (*(x) = 0)
190 #define FD_SET(f, x) (*(x) = 1<<f)
195 static char command_chars[] = "\f qh?en#sdkriIutHo";
197 static char command_chars[] = "\f qh?en#sdkriIutH";
199 /* these defines enumerate the "strchr"s of the commands in command_chars */
205 #define CMD_OSLIMIT 4 /* terminals with OS can only handle commands */
206 #define CMD_errors 5 /* less than or equal to CMD_OSLIMIT */
207 #define CMD_number1 6
208 #define CMD_number2 7
210 #define CMD_displays 9
212 #define CMD_renice 11
213 #define CMD_idletog 12
214 #define CMD_idletog2 13
216 #define CMD_selftog 15
217 #define CMD_thrtog 16
222 /* set the buffer for stdout */
225 debug = fopen("debug.run", "w");
226 setbuffer(stdout, NULL, 0);
228 setbuffer(stdout, stdoutbuf, Buffersize);
234 if ((myname = strrchr(argv[0], '/')) == 0)
244 /* initialize some selection options */
252 /* get preset options from the environment */
253 if ((env_top = getenv("TOP")) != NULL)
255 av = preset_argv = argparse(env_top, &preset_argc);
258 /* set the dummy argument to an explanatory message, in case
259 getopt encounters a bad argument */
260 preset_argv[0] = "while processing environment";
263 /* process options */
265 /* if we're done doing the presets, then process the real arguments */
266 if (preset_argc == 0)
271 /* this should keep getopt happy... */
275 while ((i = getopt(ac, av, "SIHbinquvs:d:U:o:t")) != EOF)
279 case 'v': /* show version number */
280 fprintf(stderr, "%s: version %s\n",
281 myname, version_string());
285 case 'u': /* toggle uid/username display */
286 do_unames = !do_unames;
289 case 'U': /* display only username's processes */
290 if ((ps.uid = userid(optarg)) == -1)
292 fprintf(stderr, "%s: unknown user\n", optarg);
297 case 'S': /* show system processes */
298 ps.system = !ps.system;
301 case 'I': /* show idle processes */
305 case 'i': /* go interactive regardless */
309 case 'n': /* batch, or non-interactive */
314 case 'd': /* number of displays to show */
315 if ((i = atoiwi(optarg)) == Invalid || i == 0)
318 "%s: warning: display count should be positive -- option ignored\n",
329 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
332 "%s: warning: seconds delay should be positive -- using default\n",
334 delay = Default_DELAY;
339 case 'q': /* be quick about it */
340 /* only allow this if user is really root */
343 /* be very un-nice! */
349 "%s: warning: `-q' option can only be used by root\n",
355 case 'o': /* select sort order */
360 "%s: this platform does not support arbitrary ordering. Sorry.\n",
367 ps.self = (ps.self == -1) ? getpid() : -1;
371 ps.thread = !ps.thread;
377 Usage: %s [-HISbinqut] [-d x] [-s x] [-o field] [-U username] [number]\n",
378 version_string(), myname);
383 /* get count of top processes to display (if any) */
386 if ((topn = atoiwi(av[optind])) == Invalid)
389 "%s: warning: process display count should be non-negative -- using default\n",
393 #if Default_TOPN == Infinity
396 topn_specified = Yes;
401 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
405 /* repeat only if we really did the preset arguments */
408 /* set constants for username/uid display correctly */
411 uname_field = " UID ";
415 /* initialize the kernel memory interface */
416 if (machine_init(&statics) == -1)
422 /* determine sorting order index, if necessary */
423 if (order_name != NULL)
425 if ((order_index = string_index(order_name, statics.order_names)) == -1)
429 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
431 fprintf(stderr, "\tTry one of these:");
432 pp = statics.order_names;
435 fprintf(stderr, " %s", *pp++);
443 #ifdef no_initialization_needed
444 /* initialize the hashing stuff */
451 /* initialize termcap */
452 init_termcap(interactive);
454 /* get the string to use for the process area header */
455 header_text = format_header(uname_field);
457 /* initialize display interface */
458 if ((max_topn = display_init(&statics)) == -1)
460 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
464 /* print warning if user requested more processes than we can display */
468 "%s: warning: this terminal can only display %d processes.\n",
473 /* adjust for topn == Infinity */
474 if (topn == Infinity)
477 * For smart terminals, infinity really means everything that can
478 * be displayed, or Largest.
479 * On dumb terminals, infinity means every process in the system!
480 * We only really want to do that if it was explicitly specified.
481 * This is always the case when "Default_TOPN != Infinity". But if
482 * topn wasn't explicitly specified and we are on a dumb terminal
483 * and the default is Infinity, then (and only then) we use
484 * "Nominal_TOPN" instead.
486 #if Default_TOPN == Infinity
487 topn = smart_terminal ? Largest :
488 (topn_specified ? Largest : Nominal_TOPN);
494 /* set header display accordingly */
495 display_header(topn > 0);
497 /* determine interactive state */
498 if (interactive == Maybe)
500 interactive = smart_terminal;
503 /* if # of displays not specified, fill it in */
506 displays = smart_terminal ? Infinity : 1;
509 /* hold interrupt signals while setting up the screen and the handlers */
515 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
518 (void) signal(SIGINT, leave);
519 (void) signal(SIGQUIT, leave);
520 (void) signal(SIGTSTP, tstop);
522 (void) signal(SIGWINCH, winch);
529 (void) sigsetmask(old_sigmask);
533 fputs("....", stderr);
534 fflush(stderr); /* why must I do this? */
535 sleep((unsigned)(3 * warnings));
542 * main loop -- repeat while display count is positive or while it
543 * indicates infinity (by being -1)
546 while ((displays == -1) || (displays-- > 0))
548 /* get the current stats */
549 get_system_info(&system_info);
551 /* get the current set of processes */
553 get_process_info(&system_info,
556 proc_compares[order_index]);
561 /* display the load averages */
562 (*d_loadave)(system_info.last_pid,
563 system_info.load_avg);
565 /* display the current time */
566 /* this method of getting the time SHOULD be fairly portable */
568 i_uptime(&system_info.boottime, &curr_time);
569 i_timeofday(&curr_time);
571 /* display process state breakdown */
572 (*d_procstates)(system_info.p_total,
573 system_info.procstates);
575 /* display the cpu state percentage breakdown */
576 if (dostates) /* but not the first time */
578 (*d_cpustates)(system_info.cpustates);
582 /* we'll do it next time */
594 /* display memory stats */
595 (*d_memory)(system_info.memory);
597 /* display swap stats */
598 (*d_swap)(system_info.swap);
600 /* handle message area */
603 /* update the header area */
604 (*d_header)(header_text);
608 /* determine number of processes to actually display */
609 /* this number will be the smallest of: active processes,
610 number user requested, number current screen accomodates */
611 active_procs = system_info.P_ACTIVE;
612 if (active_procs > topn)
616 if (active_procs > max_topn)
618 active_procs = max_topn;
621 /* now show the top "n" processes. */
622 for (i = 0; i < active_procs; i++)
624 (*d_process)(i, format_next_process(processes, get_userid));
632 /* do end-screen processing */
635 /* now, flush the output buffer */
636 if (fflush(stdout) != 0)
638 new_message(MT_standout, " Write error on stdout");
644 /* only do the rest if we have more displays to show */
647 /* switch out for new display on smart terminals */
656 d_loadave = u_loadave;
657 d_procstates = u_procstates;
658 d_cpustates = u_cpustates;
661 d_message = u_message;
663 d_process = u_process;
671 (void) signal(SIGALRM, onalrm);
672 (void) alarm((unsigned)delay);
674 /* wait for the rest of it .... */
677 else while (no_command)
679 /* assume valid command unless told otherwise */
682 /* set up arguments for select with timeout */
684 FD_SET(0, &readfds); /* for standard input */
685 timeout.tv_sec = delay;
694 /* move to the lower left */
698 /* default the signal handler action */
699 (void) signal(SIGTSTP, SIG_DFL);
701 /* unblock the signal and send ourselves one */
705 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
707 (void) kill(0, SIGTSTP);
709 /* reset the signal handler */
710 (void) signal(SIGTSTP, tstop);
720 /* reascertain the screen dimensions */
723 /* tell display to resize */
724 max_topn = display_resize();
726 /* reset the signal handler */
727 (void) signal(SIGWINCH, winch);
734 /* wait for either input or the end of the delay period */
735 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
736 if (sel_ret < 0 && errno != EINTR)
743 /* something to read -- clear the message area first */
746 /* now read it and convert to command strchr */
747 /* (use "change" as a temporary to hold strchr) */
748 if (read(0, &ch, 1) != 1)
750 /* read error: either 0 or -1 */
751 new_message(MT_standout, " Read error on stdin");
756 if ((iptr = strchr(command_chars, ch)) == NULL)
758 if (ch != '\r' && ch != '\n')
760 /* illegal command */
761 new_message(MT_standout, " Command not understood");
768 change = iptr - command_chars;
769 if (overstrike && change > CMD_OSLIMIT)
772 new_message(MT_standout,
773 " Command cannot be handled by this terminal");
779 case CMD_redraw: /* redraw screen */
783 case CMD_update: /* merely update display */
784 /* is the load average high? */
785 if (system_info.load_avg[0] > LoadMax)
787 /* yes, go home for visual feedback */
793 case CMD_quit: /* quit */
798 case CMD_help1: /* help */
803 standout("Hit any key to continue: ");
805 (void) read(0, &ch, 1);
808 case CMD_errors: /* show errors */
809 if (error_count() == 0)
811 new_message(MT_standout,
812 " Currently no errors to report.");
821 standout("Hit any key to continue: ");
823 (void) read(0, &ch, 1);
827 case CMD_number1: /* new number */
829 new_message(MT_standout,
830 "Number of processes to show: ");
831 newval = readline(tempbuf1, 8, Yes);
834 if (newval > max_topn)
836 new_message(MT_standout | MT_delayed,
837 " This terminal can only display %d processes.",
844 /* inhibit the header */
847 else if (newval > topn && topn == 0)
849 /* redraw the header */
857 case CMD_delay: /* new seconds delay */
858 new_message(MT_standout, "Seconds to delay: ");
859 if ((i = readline(tempbuf1, 8, Yes)) > -1)
861 if ((delay = i) == 0 && getuid() != 0)
869 case CMD_displays: /* change display count */
870 new_message(MT_standout,
871 "Displays to show (currently %s): ",
872 displays == -1 ? "infinite" :
874 if ((i = readline(tempbuf1, 10, Yes)) > 0)
885 case CMD_kill: /* kill program */
886 new_message(0, "kill ");
887 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
889 if ((errmsg = kill_procs(tempbuf2)) != NULL)
891 new_message(MT_standout, "%s", errmsg);
902 case CMD_renice: /* renice program */
903 new_message(0, "renice ");
904 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
906 if ((errmsg = renice_procs(tempbuf2)) != NULL)
908 new_message(MT_standout, "%s", errmsg);
922 new_message(MT_standout | MT_delayed,
923 " %sisplaying idle processes.",
924 ps.idle ? "D" : "Not d");
929 ps.self = (ps.self == -1) ? getpid() : -1;
930 new_message(MT_standout | MT_delayed,
931 " %sisplaying self.",
932 (ps.self == -1) ? "D" : "Not d");
937 new_message(MT_standout,
938 "Username to show: ");
939 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
941 if (tempbuf2[0] == '+' &&
946 else if ((i = userid(tempbuf2)) == -1)
948 new_message(MT_standout,
949 " %s: unknown user", tempbuf2);
965 ps.thread = !ps.thread;
966 new_message(MT_standout | MT_delayed,
967 " %sisplaying threads.",
968 ps.thread ? "D" : "Not d");
973 new_message(MT_standout,
975 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
977 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
979 new_message(MT_standout,
980 " %s: unrecognized sorting order", tempbuf2);
997 new_message(MT_standout, " BAD CASE IN SWITCH!");
1002 /* flush out stuff that may have been written */
1017 * reset_display() - reset all the display routine pointers so that entire
1018 * screen will get redrawn.
1024 d_loadave = i_loadave;
1025 d_procstates = i_procstates;
1026 d_cpustates = i_cpustates;
1027 d_memory = i_memory;
1029 d_message = i_message;
1030 d_header = i_header;
1031 d_process = i_process;
1038 sigret_t leave() /* exit under normal conditions -- INT handler */
1044 sigret_t tstop(i) /* SIGTSTP handler */
1053 sigret_t winch(i) /* SIGWINCH handler */
1062 void quit(status) /* exit under duress */
1072 sigret_t onalrm() /* SIGALRM handler */
1075 /* this is only used in batch mode to break out of the pause() */