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
16 * $FreeBSD: src/contrib/top/top.c,v 1.4.6.5 2002/08/11 17:09:25 dwmalone Exp $
17 * $DragonFly: src/contrib/top/top.c,v 1.2 2003/06/17 04:24:07 dillon Exp $
21 * See the file "Changes" for information on version-to-version changes.
25 * This file contains "main" and other high-level routines.
29 * The following preprocessor variables, when defined, are used to
30 * distinguish between different Unix implementations:
32 * SIGHOLD - use SVR4 sighold function when defined
33 * SIGRELSE - use SVR4 sigrelse function when defined
34 * FD_SET - macros FD_SET and FD_ZERO are used when defined
44 /* includes specific to top */
45 #include "display.h" /* interface to display package */
46 #include "screen.h" /* interface to screen package */
48 #include "top.local.h"
53 /* Size of the stdio buffer given to stdout */
54 #define Buffersize 2048
56 /* The buffer that stdio will use */
57 char stdoutbuf[Buffersize];
59 /* build Signal masks */
60 #define Smask(s) (1 << ((s) - 1))
66 /* imported from screen.c */
67 extern int overstrike;
69 /* signal handling routines */
77 volatile sig_atomic_t leaveflag;
78 volatile sig_atomic_t tstopflag;
79 volatile sig_atomic_t winchflag;
81 /* internal routines */
84 /* values which need to be accessed by signal handlers */
85 static int max_topn; /* maximum displayable processes */
87 /* miscellaneous things */
91 /* routines that don't return int */
99 extern int (*proc_compares[])();
101 extern int proc_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#sdkriIuto";
198 static char command_chars[] = "\f qh?en#sdkriIut";
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
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 */
251 /* get preset options from the environment */
252 if ((env_top = getenv("TOP")) != NULL)
254 av = preset_argv = argparse(env_top, &preset_argc);
257 /* set the dummy argument to an explanatory message, in case
258 getopt encounters a bad argument */
259 preset_argv[0] = "while processing environment";
262 /* process options */
264 /* if we're done doing the presets, then process the real arguments */
265 if (preset_argc == 0)
270 /* this should keep getopt happy... */
274 while ((i = getopt(ac, av, "SIbinquvs:d:U:o:t")) != EOF)
278 case 'v': /* show version number */
279 fprintf(stderr, "%s: version %s\n",
280 myname, version_string());
284 case 'u': /* toggle uid/username display */
285 do_unames = !do_unames;
288 case 'U': /* display only username's processes */
289 if ((ps.uid = userid(optarg)) == -1)
291 fprintf(stderr, "%s: unknown user\n", optarg);
296 case 'S': /* show system processes */
297 ps.system = !ps.system;
300 case 'I': /* show idle processes */
304 case 'i': /* go interactive regardless */
308 case 'n': /* batch, or non-interactive */
313 case 'd': /* number of displays to show */
314 if ((i = atoiwi(optarg)) == Invalid || i == 0)
317 "%s: warning: display count should be positive -- option ignored\n",
328 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
331 "%s: warning: seconds delay should be positive -- using default\n",
333 delay = Default_DELAY;
338 case 'q': /* be quick about it */
339 /* only allow this if user is really root */
342 /* be very un-nice! */
348 "%s: warning: `-q' option can only be used by root\n",
354 case 'o': /* select sort order */
359 "%s: this platform does not support arbitrary ordering. Sorry.\n",
366 ps.self = (ps.self == -1) ? getpid() : -1;
372 Usage: %s [-ISbinqut] [-d x] [-s x] [-o field] [-U username] [number]\n",
373 version_string(), myname);
378 /* get count of top processes to display (if any) */
381 if ((topn = atoiwi(av[optind])) == Invalid)
384 "%s: warning: process display count should be non-negative -- using default\n",
388 #if Default_TOPN == Infinity
391 topn_specified = Yes;
396 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
400 /* repeat only if we really did the preset arguments */
403 /* set constants for username/uid display correctly */
406 uname_field = " UID ";
410 /* initialize the kernel memory interface */
411 if (machine_init(&statics) == -1)
417 /* determine sorting order index, if necessary */
418 if (order_name != NULL)
420 if ((order_index = string_index(order_name, statics.order_names)) == -1)
424 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
426 fprintf(stderr, "\tTry one of these:");
427 pp = statics.order_names;
430 fprintf(stderr, " %s", *pp++);
438 #ifdef no_initialization_needed
439 /* initialize the hashing stuff */
446 /* initialize termcap */
447 init_termcap(interactive);
449 /* get the string to use for the process area header */
450 header_text = format_header(uname_field);
452 /* initialize display interface */
453 if ((max_topn = display_init(&statics)) == -1)
455 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
459 /* print warning if user requested more processes than we can display */
463 "%s: warning: this terminal can only display %d processes.\n",
468 /* adjust for topn == Infinity */
469 if (topn == Infinity)
472 * For smart terminals, infinity really means everything that can
473 * be displayed, or Largest.
474 * On dumb terminals, infinity means every process in the system!
475 * We only really want to do that if it was explicitly specified.
476 * This is always the case when "Default_TOPN != Infinity". But if
477 * topn wasn't explicitly specified and we are on a dumb terminal
478 * and the default is Infinity, then (and only then) we use
479 * "Nominal_TOPN" instead.
481 #if Default_TOPN == Infinity
482 topn = smart_terminal ? Largest :
483 (topn_specified ? Largest : Nominal_TOPN);
489 /* set header display accordingly */
490 display_header(topn > 0);
492 /* determine interactive state */
493 if (interactive == Maybe)
495 interactive = smart_terminal;
498 /* if # of displays not specified, fill it in */
501 displays = smart_terminal ? Infinity : 1;
504 /* hold interrupt signals while setting up the screen and the handlers */
510 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
513 (void) signal(SIGINT, leave);
514 (void) signal(SIGQUIT, leave);
515 (void) signal(SIGTSTP, tstop);
517 (void) signal(SIGWINCH, winch);
524 (void) sigsetmask(old_sigmask);
528 fputs("....", stderr);
529 fflush(stderr); /* why must I do this? */
530 sleep((unsigned)(3 * warnings));
537 * main loop -- repeat while display count is positive or while it
538 * indicates infinity (by being -1)
541 while ((displays == -1) || (displays-- > 0))
543 /* get the current stats */
544 get_system_info(&system_info);
546 /* get the current set of processes */
548 get_process_info(&system_info,
551 proc_compares[order_index]);
556 /* display the load averages */
557 (*d_loadave)(system_info.last_pid,
558 system_info.load_avg);
560 /* display the current time */
561 /* this method of getting the time SHOULD be fairly portable */
563 i_uptime(&system_info.boottime, &curr_time);
564 i_timeofday(&curr_time);
566 /* display process state breakdown */
567 (*d_procstates)(system_info.p_total,
568 system_info.procstates);
570 /* display the cpu state percentage breakdown */
571 if (dostates) /* but not the first time */
573 (*d_cpustates)(system_info.cpustates);
577 /* we'll do it next time */
589 /* display memory stats */
590 (*d_memory)(system_info.memory);
592 /* display swap stats */
593 (*d_swap)(system_info.swap);
595 /* handle message area */
598 /* update the header area */
599 (*d_header)(header_text);
603 /* determine number of processes to actually display */
604 /* this number will be the smallest of: active processes,
605 number user requested, number current screen accomodates */
606 active_procs = system_info.P_ACTIVE;
607 if (active_procs > topn)
611 if (active_procs > max_topn)
613 active_procs = max_topn;
616 /* now show the top "n" processes. */
617 for (i = 0; i < active_procs; i++)
619 (*d_process)(i, format_next_process(processes, get_userid));
627 /* do end-screen processing */
630 /* now, flush the output buffer */
631 if (fflush(stdout) != 0)
633 new_message(MT_standout, " Write error on stdout");
639 /* only do the rest if we have more displays to show */
642 /* switch out for new display on smart terminals */
651 d_loadave = u_loadave;
652 d_procstates = u_procstates;
653 d_cpustates = u_cpustates;
656 d_message = u_message;
658 d_process = u_process;
666 (void) signal(SIGALRM, onalrm);
667 (void) alarm((unsigned)delay);
669 /* wait for the rest of it .... */
672 else while (no_command)
674 /* assume valid command unless told otherwise */
677 /* set up arguments for select with timeout */
679 FD_SET(0, &readfds); /* for standard input */
680 timeout.tv_sec = delay;
689 /* move to the lower left */
693 /* default the signal handler action */
694 (void) signal(SIGTSTP, SIG_DFL);
696 /* unblock the signal and send ourselves one */
700 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
702 (void) kill(0, SIGTSTP);
704 /* reset the signal handler */
705 (void) signal(SIGTSTP, tstop);
715 /* reascertain the screen dimensions */
718 /* tell display to resize */
719 max_topn = display_resize();
721 /* reset the signal handler */
722 (void) signal(SIGWINCH, winch);
729 /* wait for either input or the end of the delay period */
730 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
731 if (sel_ret < 0 && errno != EINTR)
738 /* something to read -- clear the message area first */
741 /* now read it and convert to command strchr */
742 /* (use "change" as a temporary to hold strchr) */
743 if (read(0, &ch, 1) != 1)
745 /* read error: either 0 or -1 */
746 new_message(MT_standout, " Read error on stdin");
751 if ((iptr = strchr(command_chars, ch)) == NULL)
753 if (ch != '\r' && ch != '\n')
755 /* illegal command */
756 new_message(MT_standout, " Command not understood");
763 change = iptr - command_chars;
764 if (overstrike && change > CMD_OSLIMIT)
767 new_message(MT_standout,
768 " Command cannot be handled by this terminal");
774 case CMD_redraw: /* redraw screen */
778 case CMD_update: /* merely update display */
779 /* is the load average high? */
780 if (system_info.load_avg[0] > LoadMax)
782 /* yes, go home for visual feedback */
788 case CMD_quit: /* quit */
793 case CMD_help1: /* help */
798 standout("Hit any key to continue: ");
800 (void) read(0, &ch, 1);
803 case CMD_errors: /* show errors */
804 if (error_count() == 0)
806 new_message(MT_standout,
807 " Currently no errors to report.");
816 standout("Hit any key to continue: ");
818 (void) read(0, &ch, 1);
822 case CMD_number1: /* new number */
824 new_message(MT_standout,
825 "Number of processes to show: ");
826 newval = readline(tempbuf1, 8, Yes);
829 if (newval > max_topn)
831 new_message(MT_standout | MT_delayed,
832 " This terminal can only display %d processes.",
839 /* inhibit the header */
842 else if (newval > topn && topn == 0)
844 /* redraw the header */
852 case CMD_delay: /* new seconds delay */
853 new_message(MT_standout, "Seconds to delay: ");
854 if ((i = readline(tempbuf1, 8, Yes)) > -1)
856 if ((delay = i) == 0 && getuid() != 0)
864 case CMD_displays: /* change display count */
865 new_message(MT_standout,
866 "Displays to show (currently %s): ",
867 displays == -1 ? "infinite" :
869 if ((i = readline(tempbuf1, 10, Yes)) > 0)
880 case CMD_kill: /* kill program */
881 new_message(0, "kill ");
882 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
884 if ((errmsg = kill_procs(tempbuf2)) != NULL)
886 new_message(MT_standout, "%s", errmsg);
897 case CMD_renice: /* renice program */
898 new_message(0, "renice ");
899 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
901 if ((errmsg = renice_procs(tempbuf2)) != NULL)
903 new_message(MT_standout, "%s", errmsg);
917 new_message(MT_standout | MT_delayed,
918 " %sisplaying idle processes.",
919 ps.idle ? "D" : "Not d");
924 ps.self = (ps.self == -1) ? getpid() : -1;
925 new_message(MT_standout | MT_delayed,
926 " %sisplaying self.",
927 (ps.self == -1) ? "D" : "Not d");
932 new_message(MT_standout,
933 "Username to show: ");
934 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
936 if (tempbuf2[0] == '+' &&
941 else if ((i = userid(tempbuf2)) == -1)
943 new_message(MT_standout,
944 " %s: unknown user", tempbuf2);
961 new_message(MT_standout,
963 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
965 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
967 new_message(MT_standout,
968 " %s: unrecognized sorting order", tempbuf2);
985 new_message(MT_standout, " BAD CASE IN SWITCH!");
990 /* flush out stuff that may have been written */
1005 * reset_display() - reset all the display routine pointers so that entire
1006 * screen will get redrawn.
1012 d_loadave = i_loadave;
1013 d_procstates = i_procstates;
1014 d_cpustates = i_cpustates;
1015 d_memory = i_memory;
1017 d_message = i_message;
1018 d_header = i_header;
1019 d_process = i_process;
1026 sigret_t leave() /* exit under normal conditions -- INT handler */
1032 sigret_t tstop(i) /* SIGTSTP handler */
1041 sigret_t winch(i) /* SIGWINCH handler */
1050 void quit(status) /* exit under duress */
1060 sigret_t onalrm() /* SIGALRM handler */
1063 /* this is only used in batch mode to break out of the pause() */