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, 1990, 1992, William LeFebvre, Northwestern University
18 * See the file "Changes" for information on version-to-version changes.
22 * This file contains "main" and other high-level routines.
26 * The following preprocessor variables, when defined, are used to
27 * distinguish between different Unix implementations:
29 * SIGHOLD - use SVR4 sighold function when defined
30 * SIGRELSE - use SVR4 sigrelse function when defined
31 * FD_SET - macros FD_SET and FD_ZERO are used when defined
40 /* includes specific to top */
41 #include "display.h" /* interface to display package */
42 #include "screen.h" /* interface to screen package */
44 #include "top.local.h"
49 /* Size of the stdio buffer given to stdout */
50 #define Buffersize 2048
52 /* The buffer that stdio will use */
53 char stdoutbuf[Buffersize];
55 /* build Signal masks */
56 #define Smask(s) (1 << ((s) - 1))
58 /* for system errors */
65 /* imported from screen.c */
66 extern int overstrike;
68 /* signal handling routines */
76 /* internal routines */
79 /* values which need to be accessed by signal handlers */
80 static int max_topn; /* maximum displayable processes */
82 /* miscellaneous things */
86 /* routines that don't return int */
94 extern int (*proc_compares[])();
96 extern int proc_compare();
100 caddr_t get_process_info();
102 /* different routines for displaying the user's identification */
103 /* (values assigned to get_userid) */
107 /* display routines that need to be predeclared */
125 /* pointers to display routines */
126 int (*d_loadave)() = i_loadave;
127 int (*d_procstates)() = i_procstates;
128 int (*d_cpustates)() = i_cpustates;
129 int (*d_memory)() = i_memory;
130 int (*d_swap)() = i_swap;
131 int (*d_message)() = i_message;
132 int (*d_header)() = i_header;
133 int (*d_process)() = i_process;
143 register int active_procs;
146 struct system_info system_info;
147 struct statics statics;
150 static char tempbuf1[50];
151 static char tempbuf2[50];
152 int old_sigmask; /* only used for BSD-style signals */
153 int topn = Default_TOPN;
154 int delay = Default_DELAY;
155 int displays = 0; /* indicates unspecified */
157 char *(*get_userid)() = username;
158 char *uname_field = "USERNAME";
166 char do_unames = Yes;
167 char interactive = Maybe;
169 #if Default_TOPN == Infinity
170 char topn_specified = No;
175 struct timeval timeout;
176 struct process_select ps;
178 char *order_name = NULL;
182 /* FD_SET and friends are not present: fake it */
184 #define FD_ZERO(x) (*(x) = 0)
185 #define FD_SET(f, x) (*(x) = f)
190 static char command_chars[] = "\f qh?en#sdkriIuto";
192 static char command_chars[] = "\f qh?en#sdkriIut";
194 /* these defines enumerate the "strchr"s of the commands in command_chars */
200 #define CMD_OSLIMIT 4 /* terminals with OS can only handle commands */
201 #define CMD_errors 5 /* less than or equal to CMD_OSLIMIT */
202 #define CMD_number1 6
203 #define CMD_number2 7
205 #define CMD_displays 9
207 #define CMD_renice 11
208 #define CMD_idletog 12
209 #define CMD_idletog2 13
211 #define CMD_selftog 15
216 /* set the buffer for stdout */
218 setbuffer(stdout, NULL, 0);
220 setbuffer(stdout, stdoutbuf, Buffersize);
226 if ((myname = strrchr(argv[0], '/')) == 0)
236 /* initialize some selection options */
243 /* get preset options from the environment */
244 if ((env_top = getenv("TOP")) != NULL)
246 av = preset_argv = argparse(env_top, &preset_argc);
249 /* set the dummy argument to an explanatory message, in case
250 getopt encounters a bad argument */
251 preset_argv[0] = "while processing environment";
254 /* process options */
256 /* if we're done doing the presets, then process the real arguments */
257 if (preset_argc == 0)
262 /* this should keep getopt happy... */
266 while ((i = getopt(ac, av, "SIbinqus:d:U:o:t")) != EOF)
270 case 'u': /* toggle uid/username display */
271 do_unames = !do_unames;
274 case 'U': /* display only username's processes */
275 if ((ps.uid = userid(optarg)) == -1)
277 fprintf(stderr, "%s: unknown user\n", optarg);
282 case 'S': /* show system processes */
283 ps.system = !ps.system;
286 case 'I': /* show idle processes */
290 case 'i': /* go interactive regardless */
294 case 'n': /* batch, or non-interactive */
299 case 'd': /* number of displays to show */
300 if ((i = atoiwi(optarg)) == Invalid || i == 0)
303 "%s: warning: display count should be positive -- option ignored\n",
314 if ((delay = atoi(optarg)) < 0)
317 "%s: warning: seconds delay should be non-negative -- using default\n",
319 delay = Default_DELAY;
324 case 'q': /* be quick about it */
325 /* only allow this if user is really root */
328 /* be very un-nice! */
334 "%s: warning: `-q' option can only be used by root\n",
340 case 'o': /* select sort order */
345 "%s: this platform does not support arbitrary ordering. Sorry.\n",
352 ps.self = (ps.self == -1) ? getpid() : -1;
358 Usage: %s [-ISbinqut] [-d x] [-s x] [-o field] [-U username] [number]\n",
359 version_string(), myname);
364 /* get count of top processes to display (if any) */
367 if ((topn = atoiwi(av[optind])) == Invalid)
370 "%s: warning: process display count should be non-negative -- using default\n",
374 #if Default_TOPN == Infinity
377 topn_specified = Yes;
382 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
386 /* repeat only if we really did the preset arguments */
389 /* set constants for username/uid display correctly */
392 uname_field = " UID ";
396 /* initialize the kernel memory interface */
397 if (machine_init(&statics) == -1)
403 /* determine sorting order index, if necessary */
404 if (order_name != NULL)
406 if ((order_index = string_index(order_name, statics.order_names)) == -1)
410 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
412 fprintf(stderr, "\tTry one of these:");
413 pp = statics.order_names;
416 fprintf(stderr, " %s", *pp++);
424 #ifdef no_initialization_needed
425 /* initialize the hashing stuff */
432 /* initialize termcap */
433 init_termcap(interactive);
435 /* get the string to use for the process area header */
436 header_text = format_header(uname_field);
438 /* initialize display interface */
439 if ((max_topn = display_init(&statics)) == -1)
441 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
445 /* print warning if user requested more processes than we can display */
449 "%s: warning: this terminal can only display %d processes.\n",
454 /* adjust for topn == Infinity */
455 if (topn == Infinity)
458 * For smart terminals, infinity really means everything that can
459 * be displayed, or Largest.
460 * On dumb terminals, infinity means every process in the system!
461 * We only really want to do that if it was explicitly specified.
462 * This is always the case when "Default_TOPN != Infinity". But if
463 * topn wasn't explicitly specified and we are on a dumb terminal
464 * and the default is Infinity, then (and only then) we use
465 * "Nominal_TOPN" instead.
467 #if Default_TOPN == Infinity
468 topn = smart_terminal ? Largest :
469 (topn_specified ? Largest : Nominal_TOPN);
475 /* set header display accordingly */
476 display_header(topn > 0);
478 /* determine interactive state */
479 if (interactive == Maybe)
481 interactive = smart_terminal;
484 /* if # of displays not specified, fill it in */
487 displays = smart_terminal ? Infinity : 1;
490 /* hold interrupt signals while setting up the screen and the handlers */
496 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
499 (void) signal(SIGINT, leave);
500 (void) signal(SIGQUIT, leave);
501 (void) signal(SIGTSTP, tstop);
503 (void) signal(SIGWINCH, winch);
510 (void) sigsetmask(old_sigmask);
514 fputs("....", stderr);
515 fflush(stderr); /* why must I do this? */
516 sleep((unsigned)(3 * warnings));
520 /* setup the jump buffer for stops */
521 if (setjmp(jmp_int) != 0)
523 /* control ends up here after an interrupt */
528 * main loop -- repeat while display count is positive or while it
529 * indicates infinity (by being -1)
532 while ((displays == -1) || (displays-- > 0))
534 /* get the current stats */
535 get_system_info(&system_info);
537 /* get the current set of processes */
539 get_process_info(&system_info,
542 proc_compares[order_index]);
547 /* display the load averages */
548 (*d_loadave)(system_info.last_pid,
549 system_info.load_avg);
551 /* display the current time */
552 /* this method of getting the time SHOULD be fairly portable */
554 i_uptime(&system_info.boottime, &curr_time);
555 i_timeofday(&curr_time);
557 /* display process state breakdown */
558 (*d_procstates)(system_info.p_total,
559 system_info.procstates);
561 /* display the cpu state percentage breakdown */
562 if (dostates) /* but not the first time */
564 (*d_cpustates)(system_info.cpustates);
568 /* we'll do it next time */
580 /* display memory stats */
581 (*d_memory)(system_info.memory);
583 /* display swap stats */
584 (*d_swap)(system_info.swap);
586 /* handle message area */
589 /* update the header area */
590 (*d_header)(header_text);
594 /* determine number of processes to actually display */
595 /* this number will be the smallest of: active processes,
596 number user requested, number current screen accomodates */
597 active_procs = system_info.p_active;
598 if (active_procs > topn)
602 if (active_procs > max_topn)
604 active_procs = max_topn;
607 /* now show the top "n" processes. */
608 for (i = 0; i < active_procs; i++)
610 (*d_process)(i, format_next_process(processes, get_userid));
618 /* do end-screen processing */
621 /* now, flush the output buffer */
624 /* only do the rest if we have more displays to show */
627 /* switch out for new display on smart terminals */
636 d_loadave = u_loadave;
637 d_procstates = u_procstates;
638 d_cpustates = u_cpustates;
641 d_message = u_message;
643 d_process = u_process;
651 (void) signal(SIGALRM, onalrm);
652 (void) alarm((unsigned)delay);
654 /* wait for the rest of it .... */
657 else while (no_command)
659 /* assume valid command unless told otherwise */
662 /* set up arguments for select with timeout */
664 FD_SET(1, &readfds); /* for standard input */
665 timeout.tv_sec = delay;
668 /* wait for either input or the end of the delay period */
669 if (select(32, &readfds, (fd_set *)NULL, (fd_set *)NULL, &timeout) > 0)
674 /* something to read -- clear the message area first */
677 /* now read it and convert to command strchr */
678 /* (use "change" as a temporary to hold strchr) */
679 (void) read(0, &ch, 1);
680 if ((iptr = strchr(command_chars, ch)) == NULL)
682 if (ch != '\r' && ch != '\n')
684 /* illegal command */
685 new_message(MT_standout, " Command not understood");
692 change = iptr - command_chars;
693 if (overstrike && change > CMD_OSLIMIT)
696 new_message(MT_standout,
697 " Command cannot be handled by this terminal");
703 case CMD_redraw: /* redraw screen */
707 case CMD_update: /* merely update display */
708 /* is the load average high? */
709 if (system_info.load_avg[0] > LoadMax)
711 /* yes, go home for visual feedback */
717 case CMD_quit: /* quit */
722 case CMD_help1: /* help */
727 standout("Hit any key to continue: ");
729 (void) read(0, &ch, 1);
732 case CMD_errors: /* show errors */
733 if (error_count() == 0)
735 new_message(MT_standout,
736 " Currently no errors to report.");
745 standout("Hit any key to continue: ");
747 (void) read(0, &ch, 1);
751 case CMD_number1: /* new number */
753 new_message(MT_standout,
754 "Number of processes to show: ");
755 newval = readline(tempbuf1, 8, Yes);
758 if (newval > max_topn)
760 new_message(MT_standout | MT_delayed,
761 " This terminal can only display %d processes.",
768 /* inhibit the header */
771 else if (newval > topn && topn == 0)
773 /* redraw the header */
781 case CMD_delay: /* new seconds delay */
782 new_message(MT_standout, "Seconds to delay: ");
783 if ((i = readline(tempbuf1, 8, Yes)) > -1)
790 case CMD_displays: /* change display count */
791 new_message(MT_standout,
792 "Displays to show (currently %s): ",
793 displays == -1 ? "infinite" :
795 if ((i = readline(tempbuf1, 10, Yes)) > 0)
806 case CMD_kill: /* kill program */
807 new_message(0, "kill ");
808 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
810 if ((errmsg = kill_procs(tempbuf2)) != NULL)
812 new_message(MT_standout, "%s", errmsg);
823 case CMD_renice: /* renice program */
824 new_message(0, "renice ");
825 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
827 if ((errmsg = renice_procs(tempbuf2)) != NULL)
829 new_message(MT_standout, "%s", errmsg);
843 new_message(MT_standout | MT_delayed,
844 " %sisplaying idle processes.",
845 ps.idle ? "D" : "Not d");
850 ps.self = (ps.self == -1) ? getpid() : -1;
851 new_message(MT_standout | MT_delayed,
852 " %sisplaying self.",
853 (ps.self == -1) ? "D" : "Not d");
858 new_message(MT_standout,
859 "Username to show: ");
860 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
862 if (tempbuf2[0] == '+' &&
867 else if ((i = userid(tempbuf2)) == -1)
869 new_message(MT_standout,
870 " %s: unknown user", tempbuf2);
887 new_message(MT_standout,
889 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
891 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
893 new_message(MT_standout,
894 " %s: unrecognized sorting order", tempbuf2);
911 new_message(MT_standout, " BAD CASE IN SWITCH!");
916 /* flush out stuff that may have been written */
928 * reset_display() - reset all the display routine pointers so that entire
929 * screen will get redrawn.
935 d_loadave = i_loadave;
936 d_procstates = i_procstates;
937 d_cpustates = i_cpustates;
940 d_message = i_message;
942 d_process = i_process;
949 sigret_t leave() /* exit under normal conditions -- INT handler */
956 sigret_t tstop(i) /* SIGTSTP handler */
961 /* move to the lower left */
965 /* default the signal handler action */
966 (void) signal(SIGTSTP, SIG_DFL);
968 /* unblock the signal and send ourselves one */
972 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
974 (void) kill(0, SIGTSTP);
976 /* reset the signal handler */
977 (void) signal(SIGTSTP, tstop);
982 /* jump to appropriate place */
989 sigret_t winch(i) /* SIGWINCH handler */
994 /* reascertain the screen dimensions */
997 /* tell display to resize */
998 max_topn = display_resize();
1000 /* reset the signal handler */
1001 (void) signal(SIGWINCH, winch);
1003 /* jump to appropriate place */
1004 longjmp(jmp_int, 1);
1008 void quit(status) /* exit under duress */
1018 sigret_t onalrm() /* SIGALRM handler */
1021 /* this is only used in batch mode to break out of the pause() */