1 const char *copyright =
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.4 2006/10/03 12:20:11 y0netan1 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
47 /* includes specific to top */
48 #include "display.h" /* interface to display package */
49 #include "screen.h" /* interface to screen package */
51 #include "top.local.h"
58 /* Size of the stdio buffer given to stdout */
59 #define Buffersize 2048
61 /* The buffer that stdio will use */
62 char stdoutbuf[Buffersize];
64 /* build Signal masks */
65 #define Smask(s) (1 << ((s) - 1))
71 /* imported from screen.c */
72 extern int overstrike;
74 /* signal handling routines */
75 sigret_t leave(int signo);
76 sigret_t onalrm(int signo);
77 sigret_t tstop(int signo);
79 sigret_t mywinch(int signo);
82 volatile sig_atomic_t leaveflag;
83 volatile sig_atomic_t tstopflag;
84 volatile sig_atomic_t winchflag;
86 /* internal routines */
89 /* values which need to be accessed by signal handlers */
90 static int max_topn; /* maximum displayable processes */
92 static void reset_display(void);
94 /* miscellaneous things */
95 const char *myname = "top";
99 extern int (*proc_compares[])(const void *, const void *);
101 extern int proc_compare(const void *, const void *);
104 /* pointers to display routines */
105 void (*d_loadave)(int, double *) = i_loadave;
106 void (*d_procstates)(int, int *) = i_procstates;
107 void (*d_cpustates)(struct system_info *) = i_cpustates;
108 void (*d_memory)(int *) = i_memory;
109 void (*d_swap)(int *) = i_swap;
110 void (*d_message)(void) = i_message;
111 void (*d_header)(char *) = i_header;
112 void (*d_process)(int, char *) = i_process;
117 main(int argc, char **argv)
123 struct system_info system_info;
124 struct statics statics;
127 static char tempbuf1[50];
128 static char tempbuf2[50];
129 int old_sigmask; /* only used for BSD-style signals */
130 int topn = Default_TOPN;
131 int delay = Default_DELAY;
132 int displays = 0; /* indicates unspecified */
135 char *(*get_userid)(long) = username;
136 const char *uname_field = "USERNAME";
144 char do_unames = Yes;
145 char interactive = Maybe;
147 #if Default_TOPN == Infinity
148 char topn_specified = No;
153 struct timeval mytimeout;
154 struct process_select ps;
156 char *order_name = NULL;
160 /* FD_SET and friends are not present: fake it */
162 #define FD_ZERO(x) (*(x) = 0)
163 #define FD_SET(f, x) (*(x) = 1<<f)
168 static char command_chars[] = "\f qh?en#sdkriIutTOSo";
170 static char command_chars[] = "\f qh?en#sdkriIutTOSO";
172 /* these defines enumerate the "strchr"s of the commands in command_chars */
178 #define CMD_OSLIMIT 4 /* terminals with OS can only handle commands */
179 #define CMD_errors 5 /* less than or equal to CMD_OSLIMIT */
180 #define CMD_number1 6
181 #define CMD_number2 7
183 #define CMD_displays 9
185 #define CMD_renice 11
186 #define CMD_idletog 12
187 #define CMD_idletog2 13
189 #define CMD_selftog 15
190 #define CMD_threads 16
191 #define CMD_othreads 17
192 #define CMD_system 18
197 /* set the buffer for stdout */
200 debug = fopen("debug.run", "w");
201 setbuffer(stdout, NULL, 0);
203 setbuffer(stdout, stdoutbuf, Buffersize);
209 if ((myname = strrchr(argv[0], '/')) == 0)
219 /* initialize some selection options */
224 ps.only_threads = No;
228 /* get preset options from the environment */
229 if ((env_top = getenv("TOP")) != NULL)
231 av = preset_argv = argparse(env_top, &preset_argc);
234 /* set the dummy argument to an explanatory message, in case
235 getopt encounters a bad argument */
236 preset_argv[0] = strdup("while processing environment");
239 /* process options */
241 /* if we're done doing the presets, then process the real arguments */
242 if (preset_argc == 0)
247 /* this should keep getopt happy... */
251 while ((i = getopt(ac, av, "SITONbinquvs:d:U:o:t")) != EOF)
255 case 'v': /* show version number */
256 fprintf(stderr, "%s: version %s\n",
257 myname, version_string());
261 case 'u': /* toggle uid/username display */
262 do_unames = !do_unames;
265 case 'U': /* display only username's processes */
266 if ((ps.uid = userid(optarg)) == -1)
268 fprintf(stderr, "%s: unknown user\n", optarg);
273 case 'S': /* show system processes */
274 ps.system = !ps.system;
277 case 'I': /* show idle processes */
282 ps.only_threads = !ps.only_threads; /* only threads */
286 ps.threads = !ps.threads; /* show threads */
289 case 'i': /* go interactive regardless */
293 case 'n': /* batch, or non-interactive */
298 case 'd': /* number of displays to show */
299 if ((i = atoiwi(optarg)) == Invalid || i == 0)
302 "%s: warning: display count should be positive -- option ignored\n",
313 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
316 "%s: warning: seconds delay should be positive -- using default\n",
318 delay = Default_DELAY;
323 case 'q': /* be quick about it */
324 /* only allow this if user is really root */
327 /* be very un-nice! */
333 "%s: warning: `-q' option can only be used by root\n",
339 case 'o': /* select sort order */
344 "%s: this platform does not support arbitrary ordering. Sorry.\n",
351 ps.self = (ps.self == -1) ? getpid() : -1;
357 Usage: %s [-ISbinqut] [-d x] [-s x] [-o field] [-U username] [number]\n",
358 version_string(), myname);
363 /* get count of top processes to display (if any) */
366 if ((topn = atoiwi(av[optind])) == Invalid)
369 "%s: warning: process display count should be non-negative -- using default\n",
373 #if Default_TOPN == Infinity
376 topn_specified = Yes;
381 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
385 /* repeat only if we really did the preset arguments */
388 /* set constants for username/uid display correctly */
391 uname_field = " UID ";
395 /* initialize the kernel memory interface */
396 if (machine_init(&statics) == -1)
402 /* determine sorting order index, if necessary */
403 if (order_name != NULL)
405 if ((order_index = string_index(order_name, statics.order_names)) == -1)
409 fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
411 fprintf(stderr, "\tTry one of these:");
412 pp = statics.order_names;
415 fprintf(stderr, " %s", *pp++);
423 #ifdef no_initialization_needed
424 /* initialize the hashing stuff */
431 /* initialize termcap */
432 init_termcap(interactive);
434 /* get the string to use for the process area header */
435 header_text = format_header(uname_field);
437 /* initialize display interface */
438 if ((max_topn = display_init(&statics)) == -1)
440 fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
444 /* print warning if user requested more processes than we can display */
448 "%s: warning: this terminal can only display %d processes.\n",
453 /* adjust for topn == Infinity */
454 if (topn == Infinity)
457 * For smart terminals, infinity really means everything that can
458 * be displayed, or Largest.
459 * On dumb terminals, infinity means every process in the system!
460 * We only really want to do that if it was explicitly specified.
461 * This is always the case when "Default_TOPN != Infinity". But if
462 * topn wasn't explicitly specified and we are on a dumb terminal
463 * and the default is Infinity, then (and only then) we use
464 * "Nominal_TOPN" instead.
466 #if Default_TOPN == Infinity
467 topn = smart_terminal ? Largest :
468 (topn_specified ? Largest : Nominal_TOPN);
474 /* set header display accordingly */
475 display_header(topn > 0);
477 /* determine interactive state */
478 if (interactive == Maybe)
480 interactive = smart_terminal;
483 /* if # of displays not specified, fill it in */
486 displays = smart_terminal ? Infinity : 1;
489 /* hold interrupt signals while setting up the screen and the handlers */
495 old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
498 (void) signal(SIGINT, leave);
499 (void) signal(SIGQUIT, leave);
500 (void) signal(SIGTSTP, tstop);
502 (void) signal(SIGWINCH, mywinch);
509 (void) sigsetmask(old_sigmask);
513 fputs("....", stderr);
514 fflush(stderr); /* why must I do this? */
515 sleep((unsigned)(3 * warnings));
522 * main loop -- repeat while display count is positive or while it
523 * indicates infinity (by being -1)
526 while ((displays == -1) || (displays-- > 0))
528 /* get the current stats */
529 get_system_info(&system_info);
531 /* get the current set of processes */
533 get_process_info(&system_info,
536 proc_compares[order_index]);
541 /* display the load averages */
542 (*d_loadave)(system_info.last_pid,
543 system_info.load_avg);
545 /* display the current time */
546 /* this method of getting the time SHOULD be fairly portable */
548 i_uptime(&system_info.boottime, &curr_time);
549 i_timeofday(&curr_time);
551 /* display process state breakdown */
552 (*d_procstates)(system_info.p_total,
553 system_info.procstates);
555 /* display the cpu state percentage breakdown */
556 if (dostates) /* but not the first time */
558 (*d_cpustates)(&system_info);
562 /* we'll do it next time */
565 z_cpustates(&system_info);
574 /* display memory stats */
575 (*d_memory)(system_info.memory);
577 /* display swap stats */
578 (*d_swap)(system_info.swap);
580 /* handle message area */
583 /* update the header area */
584 (*d_header)(header_text);
588 /* determine number of processes to actually display */
589 /* this number will be the smallest of: active processes,
590 number user requested, number current screen accomodates */
591 active_procs = system_info.P_ACTIVE;
592 if (active_procs > topn)
596 if (active_procs > max_topn)
598 active_procs = max_topn;
601 /* now show the top "n" processes. */
602 for (i = 0; i < active_procs; i++)
604 (*d_process)(i, format_next_process(processes, get_userid));
612 /* do end-screen processing */
615 /* now, flush the output buffer */
616 if (fflush(stdout) != 0)
618 new_message(MT_standout, " Write error on stdout");
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 = i_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(0, &readfds); /* for standard input */
665 mytimeout.tv_sec = delay;
666 mytimeout.tv_usec = 0;
674 /* move to the lower left */
678 /* default the signal handler action */
679 (void) signal(SIGTSTP, SIG_DFL);
681 /* unblock the signal and send ourselves one */
685 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
687 (void) kill(0, SIGTSTP);
689 /* reset the signal handler */
690 (void) signal(SIGTSTP, tstop);
700 /* reascertain the screen dimensions */
703 /* tell display to resize */
704 max_topn = display_resize();
706 /* reset the signal handler */
707 (void) signal(SIGWINCH, mywinch);
714 /* wait for either input or the end of the delay period */
715 sel_ret = select(2, &readfds, NULL, NULL, &mytimeout);
716 if (sel_ret < 0 && errno != EINTR)
723 /* something to read -- clear the message area first */
726 /* now read it and convert to command strchr */
727 /* (use "change" as a temporary to hold strchr) */
728 if (read(0, &ch, 1) != 1)
730 /* read error: either 0 or -1 */
731 new_message(MT_standout, " Read error on stdin");
736 if ((iptr = strchr(command_chars, ch)) == NULL)
738 if (ch != '\r' && ch != '\n')
740 /* illegal command */
741 new_message(MT_standout, " Command not understood");
748 change = iptr - command_chars;
749 if (overstrike && change > CMD_OSLIMIT)
752 new_message(MT_standout,
753 " Command cannot be handled by this terminal");
759 case CMD_redraw: /* redraw screen */
763 case CMD_update: /* merely update display */
764 /* is the load average high? */
765 if (system_info.load_avg[0] > LoadMax)
767 /* yes, go home for visual feedback */
773 case CMD_quit: /* quit */
778 case CMD_help1: /* help */
783 dostandout("Hit any key to continue: ");
785 (void) read(0, &ch, 1);
788 case CMD_errors: /* show errors */
789 if (error_count() == 0)
791 new_message(MT_standout,
792 " Currently no errors to report.");
801 dostandout("Hit any key to continue: ");
803 (void) read(0, &ch, 1);
807 case CMD_number1: /* new number */
809 new_message(MT_standout,
810 "Number of processes to show: ");
811 newval = readline(tempbuf1, 8, Yes);
814 if (newval > max_topn)
816 new_message(MT_standout | MT_delayed,
817 " This terminal can only display %d processes.",
824 /* inhibit the header */
827 else if (newval > topn && topn == 0)
829 /* redraw the header */
837 case CMD_delay: /* new seconds delay */
838 new_message(MT_standout, "Seconds to delay: ");
839 if ((i = readline(tempbuf1, 8, Yes)) > -1)
841 if ((delay = i) == 0 && getuid() != 0)
849 case CMD_displays: /* change display count */
850 new_message(MT_standout,
851 "Displays to show (currently %s): ",
852 displays == -1 ? "infinite" :
854 if ((i = readline(tempbuf1, 10, Yes)) > 0)
865 case CMD_kill: /* kill program */
866 new_message(0, "kill ");
867 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
869 if ((xerrmsg = kill_procs(tempbuf2)) != NULL)
871 new_message(MT_standout, "%s", xerrmsg);
882 case CMD_renice: /* renice program */
883 new_message(0, "renice ");
884 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
886 if ((xerrmsg = renice_procs(tempbuf2)) != NULL)
888 new_message(MT_standout, "%s", xerrmsg);
902 new_message(MT_standout | MT_delayed,
903 " %sisplaying idle processes.",
904 ps.idle ? "D" : "Not d");
909 ps.self = (ps.self == -1) ? getpid() : -1;
910 new_message(MT_standout | MT_delayed,
911 " %sisplaying self.",
912 (ps.self == -1) ? "D" : "Not d");
917 ps.threads = !ps.threads;
918 new_message(MT_standout | MT_delayed,
919 " %sisplaying threads.",
920 ps.threads ? "D" : "Not d");
925 ps.only_threads = !ps.only_threads;
926 new_message(MT_standout | MT_delayed,
928 "Only displaying threads." :
929 "Displaying threads and processes.");
934 ps.system = !ps.system;
935 new_message(MT_standout | MT_delayed,
936 " %sisplaying system processes.",
937 ps.system ? "D" : "Not d");
942 new_message(MT_standout,
943 "Username to show: ");
944 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
946 if (tempbuf2[0] == '+' &&
951 else if ((i = userid(tempbuf2)) == -1)
953 new_message(MT_standout,
954 " %s: unknown user", tempbuf2);
971 new_message(MT_standout,
973 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
975 if ((i = string_index(tempbuf2, statics.order_names)) == -1)
977 new_message(MT_standout,
978 " %s: unrecognized sorting order", tempbuf2);
995 new_message(MT_standout, " BAD CASE IN SWITCH!");
1000 /* flush out stuff that may have been written */
1016 * reset_display() - reset all the display routine pointers so that entire
1017 * screen will get redrawn.
1023 d_loadave = i_loadave;
1024 d_procstates = i_procstates;
1025 d_cpustates = i_cpustates;
1026 d_memory = i_memory;
1028 d_message = i_message;
1029 d_header = i_header;
1030 d_process = i_process;
1037 /* exit under normal conditions -- INT handler */
1039 leave(int signo __unused)
1045 tstop(int signo __unused) /* SIGTSTP handler */
1052 mywinch(int signo __unused) /* SIGWINCH handler */
1059 quit(int status) /* exit under duress */
1067 onalrm(int signo __unused) /* SIGALRM handler */
1070 /* this is only used in batch mode to break out of the pause() */