Index: head/usr.bin/top/commands.c =================================================================== --- head/usr.bin/top/commands.c (revision 334988) +++ head/usr.bin/top/commands.c (revision 334989) @@ -1,500 +1,501 @@ /* * Top users/processes display for Unix * * This program may be freely redistributed, * but this entire comment MUST remain intact. * * Copyright (c) 1984, 1989, William LeFebvre, Rice University * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University * * $FreeBSD$ */ /* * This file contains the routines that implement some of the interactive * mode commands. Note that some of the commands are implemented in-line * in "main". This is necessary because they change the global state of * "top" (i.e.: changing the number of processes to display). */ #include #include #include #include #include #include #include #include #include #include #include "commands.h" #include "top.h" #include "machine.h" static int err_compar(const void *p1, const void *p2); struct errs /* structure for a system-call error */ { int errnum; /* value of errno (that is, the actual error) */ char *arg; /* argument that caused the error */ }; static char *err_string(void); static int str_adderr(char *str, int len, int err); static int str_addarg(char *str, int len, char *arg, bool first); /* * show_help() - display the help screen; invoked in response to * either 'h' or '?'. */ const struct command all_commands[] = { {'C', "toggle the displaying of weighted CPU percentage", false, CMD_wcputog}, {'d', "change number of displays to show", false, CMD_displays}, {'e', "list errors generated by last \"kill\" or \"renice\" command", false, CMD_errors}, {'H', "toggle the displaying of threads", false, CMD_thrtog}, {'h', "show this help text", true, CMD_help}, {'?', "show this help text", true, CMD_help}, {'i', "toggle the displaying of idle processes", false, CMD_idletog}, {'I', "toggle the displaying of idle processes", false, CMD_idletog}, {'j', "toggle the displaying of jail ID", false, CMD_jidtog}, {'J', "display processes for only one jail (+ selects all jails)", false, CMD_jail}, {'k', "kill processes; send a signal to a list of processes", false, CMD_kill}, {'q', "quit" , true, CMD_quit}, {'m', "toggle the display between 'cpu' and 'io' modes", false, CMD_viewtog}, {'n', "change number of processes to display", false, CMD_number}, {'#', "change number of processes to display", false, CMD_number}, {'o', "specify the sort order", false, CMD_order}, {'p', "display one process (+ selects all processes)", false, CMD_pid}, {'P', "toggle the displaying of per-CPU statistics", false, CMD_pcputog}, {'r', "renice a process", false, CMD_renice}, {'s', "change number of seconds to delay between updates", false, CMD_delay}, {'S', "toggle the displaying of system processes", false, CMD_viewsys}, {'a', "toggle the displaying of process titles", false, CMD_showargs}, {'T', "toggle the displaying of thread IDs", false, CMD_toggletid}, {'t', "toggle the display of this process", false, CMD_selftog}, {'u', "display processes for only one user (+ selects all users)", false, CMD_user}, {'w', "toggle the display of swap use for each process", false, CMD_swaptog}, {'z', "toggle the displaying of the system idle process", false, CMD_kidletog}, {' ', "update the display", false, CMD_update}, {0, NULL, true, CMD_NONE} }; void show_help(void) { const struct command *curcmd; printf("Top version FreeBSD, %s\n", copyright); curcmd = all_commands; while (curcmd->c != 0) { if (overstrike && !curcmd->available_to_dumb) { ++curcmd; continue; } printf("%c\t- %s\n", curcmd->c, curcmd->desc); ++curcmd; } if (overstrike) { fputs("\ Other commands are also available, but this terminal is not\n\ sophisticated enough to handle those commands gracefully.\n", stdout); } } /* * Utility routines that help with some of the commands. */ static char * next_field(char *str) { if ((str = strchr(str, ' ')) == NULL) { return(NULL); } *str = '\0'; while (*++str == ' ') /* loop */; /* if there is nothing left of the string, return NULL */ /* This fix is dedicated to Greg Earle */ return(*str == '\0' ? NULL : str); } static int scanint(char *str, int *intp) { int val = 0; char ch; /* if there is nothing left of the string, flag it as an error */ /* This fix is dedicated to Greg Earle */ if (*str == '\0') { return(-1); } while ((ch = *str++) != '\0') { if (isdigit(ch)) { val = val * 10 + (ch - '0'); } else if (isspace(ch)) { break; } else { return(-1); } } *intp = val; return(0); } /* * Some of the commands make system calls that could generate errors. * These errors are collected up in an array of structures for later * contemplation and display. Such routines return a string containing an * error message, or NULL if no errors occurred. The next few routines are * for manipulating and displaying these errors. We need an upper limit on * the number of errors, so we arbitrarily choose 20. */ #define ERRMAX 20 static struct errs errs[ERRMAX]; static int errcnt; static char err_toomany[] = " too many errors occurred"; static char err_listem[] = " Many errors occurred. Press `e' to display the list of errors."; /* These macros get used to reset and log the errors */ #define ERR_RESET errcnt = 0 #define ERROR(p, e) if (errcnt >= ERRMAX) \ { \ return(err_toomany); \ } \ else \ { \ errs[errcnt].arg = (p); \ errs[errcnt++].errnum = (e); \ } /* * err_string() - return an appropriate error string. This is what the * command will return for displaying. If no errors were logged, then * return NULL. The maximum length of the error string is defined by * "STRMAX". */ #define STRMAX 80 -char *err_string(void) +char * +err_string(void) { struct errs *errp; int cnt = 0; bool first = true; int currerr = -1; int stringlen; /* characters still available in "string" */ static char string[STRMAX]; /* if there are no errors, return NULL */ if (errcnt == 0) { return(NULL); } /* sort the errors */ qsort((char *)errs, errcnt, sizeof(struct errs), err_compar); /* need a space at the front of the error string */ string[0] = ' '; string[1] = '\0'; stringlen = STRMAX - 2; /* loop thru the sorted list, building an error string */ while (cnt < errcnt) { errp = &(errs[cnt++]); if (errp->errnum != currerr) { if (currerr != -1) { if ((stringlen = str_adderr(string, stringlen, currerr)) < 2) { return(err_listem); } strcat(string, "; "); /* we know there's more */ } currerr = errp->errnum; first = true; } if ((stringlen = str_addarg(string, stringlen, errp->arg, first)) ==0) { return(err_listem); } first = false; } /* add final message */ stringlen = str_adderr(string, stringlen, currerr); /* return the error string */ return(stringlen == 0 ? err_listem : string); } /* * str_adderr(str, len, err) - add an explanation of error "err" to * the string "str". */ static int str_adderr(char *str, int len, int err) { const char *msg; int msglen; msg = err == 0 ? "Not a number" : strerror(err); msglen = strlen(msg) + 2; if (len <= msglen) { return(0); } strcat(str, ": "); strcat(str, msg); return(len - msglen); } /* * str_addarg(str, len, arg, first) - add the string argument "arg" to * the string "str". This is the first in the group when "first" * is set (indicating that a comma should NOT be added to the front). */ static int str_addarg(char str[], int len, char arg[], bool first) { int arglen; arglen = strlen(arg); if (!first) { arglen += 2; } if (len <= arglen) { return(0); } if (!first) { strcat(str, ", "); } strcat(str, arg); return(len - arglen); } /* * err_compar(p1, p2) - comparison routine used by "qsort" * for sorting errors. */ static int err_compar(const void *p1, const void *p2) { int result; const struct errs * const g1 = (const struct errs * const)p1; const struct errs * const g2 = (const struct errs * const)p2; if ((result = g1->errnum - g2->errnum) == 0) { return(strcmp(g1->arg, g2->arg)); } return(result); } /* * error_count() - return the number of errors currently logged. */ int error_count(void) { return(errcnt); } /* * show_errors() - display on stdout the current log of errors. */ void show_errors(void) { int cnt = 0; struct errs *errp = errs; printf("%d error%s:\n\n", errcnt, errcnt == 1 ? "" : "s"); while (cnt++ < errcnt) { printf("%5s: %s\n", errp->arg, errp->errnum == 0 ? "Not a number" : strerror(errp->errnum)); errp++; } } static const char no_proc_specified[] = " no processes specified"; static const char invalid_signal_number[] = " invalid_signal_number"; static const char bad_signal_name[] = " bad signal name"; static const char bad_pri_value[] = " bad priority value"; static int signame_to_signum(const char * sig) { int n; if (strncasecmp(sig, "SIG", 3) == 0) sig += 3; for (n = 1; n < sys_nsig; n++) { if (!strcasecmp(sys_signame[n], sig)) return (n); } return (-1); } /* * kill_procs(str) - send signals to processes, much like the "kill" * command does; invoked in response to 'k'. */ const char * kill_procs(char *str) { char *nptr; int signum = SIGTERM; /* default */ int procnum; /* reset error array */ ERR_RESET; /* skip over leading white space */ while (isspace(*str)) str++; if (str[0] == '-') { /* explicit signal specified */ if ((nptr = next_field(str)) == NULL) { return(no_proc_specified); } if (isdigit(str[1])) { scanint(str + 1, &signum); if (signum <= 0 || signum >= NSIG) { return(invalid_signal_number); } } else { signum = signame_to_signum(str + 1); /* was it ever found */ if (signum == -1 ) { return(bad_signal_name); } } /* put the new pointer in place */ str = nptr; } /* loop thru the string, killing processes */ do { if (scanint(str, &procnum) == -1) { ERROR(str, 0); } else { /* go in for the kill */ if (kill(procnum, signum) == -1) { /* chalk up an error */ ERROR(str, errno); } } } while ((str = next_field(str)) != NULL); /* return appropriate error string */ return(err_string()); } /* * renice_procs(str) - change the "nice" of processes, much like the * "renice" command does; invoked in response to 'r'. */ const char * renice_procs(char *str) { char negate; int prio; int procnum; ERR_RESET; /* allow for negative priority values */ if ((negate = (*str == '-')) != 0) { /* move past the minus sign */ str++; } /* use procnum as a temporary holding place and get the number */ procnum = scanint(str, &prio); /* negate if necessary */ if (negate) { prio = -prio; } /* check for validity */ if (procnum == -1 || prio < PRIO_MIN || prio > PRIO_MAX) { return(bad_pri_value); } /* move to the first process number */ if ((str = next_field(str)) == NULL) { return(no_proc_specified); } /* loop thru the process numbers, renicing each one */ do { if (scanint(str, &procnum) == -1) { ERROR(str, 0); } if (setpriority(PRIO_PROCESS, procnum, prio) == -1) { ERROR(str, errno); } } while ((str = next_field(str)) != NULL); /* return appropriate error string */ return(err_string()); } Index: head/usr.bin/top/machine.h =================================================================== --- head/usr.bin/top/machine.h (revision 334988) +++ head/usr.bin/top/machine.h (revision 334989) @@ -1,100 +1,96 @@ /* * $FreeBSD$ */ /* * This file defines the interface between top and the machine-dependent * module. It is NOT machine dependent and should not need to be changed * for any specific machine. */ #ifndef MACHINE_H #define MACHINE_H #include #include #define NUM_AVERAGES 3 /* Log base 2 of 1024 is 10 (2^10 == 1024) */ #define LOG1024 10 /* * the statics struct is filled in by machine_init */ struct statics { const char * const *procstate_names; const char * const *cpustate_names; const char * const *memory_names; const char * const *arc_names; const char * const *carc_names; const char * const *swap_names; const char * const *order_names; int ncpus; }; /* * the system_info struct is filled in by a machine dependent routine. */ struct system_info { int last_pid; double load_avg[NUM_AVERAGES]; int p_total; int p_pactive; /* number of procs considered "active" */ int *procstates; int *cpustates; int *memory; int *arc; int *carc; int *swap; struct timeval boottime; int ncpus; }; -/* cpu_states is an array of percentages * 10. For example, - the (integer) value 105 is 10.5% (or .105). - */ - /* * the process_select struct tells get_process_info what processes * and information we are interested in seeing */ struct process_select { bool idle; /* show idle processes */ bool self; /* show self */ bool system; /* show system processes */ bool thread; /* show threads */ bool thread_id; /* show thread ids */ #define TOP_MAX_UIDS 8 int uid[TOP_MAX_UIDS]; /* only these uids (unless uid[0] == -1) */ bool wcpu; /* show weighted cpu */ int jid; /* only this jid (unless jid == -1) */ bool jail; /* show jail ID */ bool swap; /* show swap usage */ bool kidle; /* show per-CPU idle threads */ int pid; /* only this pid (unless pid == -1) */ const char *command; /* only this command (unless == NULL) */ }; /* routines defined by the machine dependent module */ const char *format_header(const char *uname_field); char *format_next_process(void* handle, char *(*get_userid)(int), int flags); void toggle_pcpustats(void); void get_system_info(struct system_info *si); int machine_init(struct statics *statics); int proc_owner(int pid); /* non-int routines typically used by the machine dependent module */ extern struct process_select ps; void * get_process_info(struct system_info *si, struct process_select *sel, int (*compare)(const void *, const void *)); #endif /* MACHINE_H */ Index: head/usr.bin/top/top.c =================================================================== --- head/usr.bin/top/top.c (revision 334988) +++ head/usr.bin/top/top.c (revision 334989) @@ -1,1239 +1,1238 @@ /*- * Top users/processes display for Unix * * This program may be freely redistributed, * but this entire comment MUST remain intact. * * Copyright (c) 1984, 1989, William LeFebvre, Rice University * Copyright (c) 1989 - 1994, William LeFebvre, Northwestern University * Copyright (c) 1994, 1995, William LeFebvre, Argonne National Laboratory * Copyright (c) 1996, William LeFebvre, Group sys Consulting * * $FreeBSD$ */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "commands.h" #include "display.h" /* interface to display package */ #include "screen.h" /* interface to screen package */ #include "top.h" #include "machine.h" #include "utils.h" #include "username.h" /* Size of the stdio buffer given to stdout */ #define Buffersize 2048 char copyright[] = "Copyright (c) 1984 through 1996, William LeFebvre"; typedef void sigret_t; /* The buffer that stdio will use */ static char stdoutbuf[Buffersize]; /* build Signal masks */ #define Smask(s) (1 << ((s) - 1)) static int fmt_flags = 0; int pcpu_stats = false; /* signal handling routines */ static sigret_t leave(int); static sigret_t tstop(int); static sigret_t top_winch(int); static volatile sig_atomic_t leaveflag; static volatile sig_atomic_t tstopflag; static volatile sig_atomic_t winchflag; /* values which need to be accessed by signal handlers */ static int max_topn; /* maximum displayable processes */ /* miscellaneous things */ struct process_select ps; const char * myname = "top"; pid_t mypid; /* pointers to display routines */ static void (*d_loadave)(int mpid, double *avenrun) = i_loadave; static void (*d_procstates)(int total, int *brkdn) = i_procstates; static void (*d_cpustates)(int *states) = i_cpustates; static void (*d_memory)(int *stats) = i_memory; static void (*d_arc)(int *stats) = i_arc; static void (*d_carc)(int *stats) = i_carc; static void (*d_swap)(int *stats) = i_swap; static void (*d_message)(void) = i_message; static void (*d_header)(const char *text) = i_header; static void (*d_process)(int line, char *thisline) = i_process; static void reset_display(void); static const struct option longopts[] = { { "cpu-display-mode", no_argument, NULL, 'C' }, /* differs from orignal */ /* D reserved */ { "thread", no_argument, NULL, 'H' }, { "idle-procs", no_argument, NULL, 'I' }, { "jail", required_argument, NULL, 'J' }, { "per-cpu", no_argument, NULL, 'P' }, { "system-procs", no_argument, NULL, 'S' }, { "thread-id", no_argument, NULL, 'T' }, /* differs from orignal */ { "user", required_argument, NULL, 'U' }, { "all", no_argument, NULL, 'a' }, { "batch", no_argument, NULL, 'b' }, /* c reserved */ { "displays", required_argument, NULL, 'd' }, { "interactive", no_argument, NULL, 'i' }, { "jail-id", no_argument, NULL, 'j' }, { "display-mode", required_argument, NULL, 'm' }, /* n is identical to batch */ { "sort-order", required_argument, NULL, 'o' }, { "pid", required_argument, NULL, 'p' }, { "quick", no_argument, NULL, 'q' }, { "delay", required_argument, NULL, 's' }, { "threads", no_argument, NULL, 't' }, { "uids", no_argument, NULL, 'u' }, { "version", no_argument, NULL, 'v' }, { "swap", no_argument, NULL, 'w' }, { "system-idle-procs", no_argument, NULL, 'z' } }; static void reset_uids(void) { for (size_t i = 0; i < TOP_MAX_UIDS; ++i) ps.uid[i] = -1; } static int add_uid(int uid) { size_t i = 0; /* Add the uid if there's room */ for (; i < TOP_MAX_UIDS; ++i) { if (ps.uid[i] == -1 || ps.uid[i] == uid) { ps.uid[i] = uid; break; } } return (i == TOP_MAX_UIDS); } static void rem_uid(int uid) { size_t i = 0; size_t where = TOP_MAX_UIDS; /* Look for the user to remove - no problem if it's not there */ for (; i < TOP_MAX_UIDS; ++i) { if (ps.uid[i] == -1) break; if (ps.uid[i] == uid) where = i; } /* Make sure we don't leave a hole in the middle */ if (where != TOP_MAX_UIDS) { ps.uid[where] = ps.uid[i-1]; ps.uid[i-1] = -1; } } static int handle_user(char *buf, size_t buflen) { int rc = 0; int uid = -1; char *buf2 = buf; new_message(MT_standout, "Username to show (+ for all): "); if (readline(buf, buflen, false) <= 0) { clear_message(); return (rc); } if (buf[0] == '+' || buf[0] == '-') { if (buf[1] == '\0') { reset_uids(); goto end; } else ++buf2; } if ((uid = userid(buf2)) == -1) { new_message(MT_standout, " %s: unknown user", buf2); rc = 1; goto end; } if (buf2 == buf) { reset_uids(); ps.uid[0] = uid; goto end; } if (buf[0] == '+') { if (add_uid(uid)) { new_message(MT_standout, " too many users, reset with '+'"); rc = 1; goto end; } } else rem_uid(uid); end: putchar('\r'); return (rc); } int main(int argc, char *argv[]) { int i; int active_procs; struct system_info system_info; struct statics statics; void * processes; static char tempbuf1[50]; static char tempbuf2[50]; int old_sigmask; /* only used for BSD-style signals */ int topn = Infinity; double delay = 2; int displays = 0; /* indicates unspecified */ int sel_ret = 0; time_t curr_time; char *(*get_userid)(int) = username; const char *uname_field = "USERNAME"; const char *header_text; char *env_top; const char **preset_argv; int preset_argc = 0; const char **av; int ac; bool dostates = false; bool do_unames = true; char interactive = 2; char warnings = 0; char topn_specified = false; char ch; char no_command = 1; struct timeval timeout; char *order_name = NULL; int order_index = 0; fd_set readfds; /* set the buffer for stdout */ #ifdef DEBUG extern FILE *debug; debug = fopen("debug.run", "w"); setbuffer(stdout, NULL, 0); #else setbuffer(stdout, stdoutbuf, Buffersize); #endif if (argc > 0) { if ((myname = strrchr(argv[0], '/')) == 0) { myname = argv[0]; } else { myname++; } } mypid = getpid(); /* get our name */ /* initialize some selection options */ ps.idle = true; ps.self = false; ps.system = false; reset_uids(); ps.thread = false; ps.wcpu = 1; ps.jid = -1; ps.jail = false; ps.swap = false; ps.kidle = true; ps.pid = -1; ps.command = NULL; ps.thread_id = false; /* get preset options from the environment */ if ((env_top = getenv("TOP")) != NULL) { av = preset_argv = argparse(env_top, &preset_argc); ac = preset_argc; /* set the dummy argument to an explanatory message, in case getopt encounters a bad argument */ preset_argv[0] = "while processing environment"; } /* process options */ do { /* if we're done doing the presets, then process the real arguments */ if (preset_argc == 0) { ac = argc; av = argv; /* this should keep getopt happy... */ optind = 1; } while ((i = getopt_long(ac, av, "CSIHPabijJ:nquvzs:d:U:m:o:p:Ttw", longopts, NULL)) != EOF) { switch(i) { case 'v': /* show version number */ fprintf(stderr, "%s: version FreeBSD\n", myname); exit(1); break; case 'u': /* toggle uid/username display */ do_unames = !do_unames; break; case 'U': /* display only username's processes */ if ((ps.uid[0] = userid(optarg)) == -1) { fprintf(stderr, "%s: unknown user\n", optarg); exit(1); } break; case 'S': /* show system processes */ ps.system = true; break; case 'I': /* show idle processes */ ps.idle = !ps.idle; break; case 'i': /* go interactive regardless */ interactive = 1; break; case 'n': /* batch, or non-interactive */ case 'b': interactive = 0; break; case 'a': fmt_flags ^= FMT_SHOWARGS; break; case 'd': /* number of displays to show */ if ((i = atoiwi(optarg)) == Invalid || i == 0) { fprintf(stderr, "%s: warning: display count should be positive -- option ignored\n", myname); warnings++; } else { displays = i; } break; case 'p': { unsigned long long num; const char *errstr; num = strtonum(optarg, 0, INT_MAX, &errstr); if (errstr != NULL || !find_pid(num)) { fprintf(stderr, "%s: unknown pid\n", optarg); exit(1); } ps.pid = (pid_t)num; ps.system = true; break; } case 's': delay = strtod(optarg, NULL); if (delay < 0) { fprintf(stderr, "%s: warning: seconds delay should be positive -- using default\n", myname); delay = 2; warnings++; } break; case 'q': /* be quick about it */ errno = 0; i = setpriority(PRIO_PROCESS, 0, PRIO_MIN); if (i == -1 && errno != 0) { fprintf(stderr, "%s: warning: `-q' option failed (%m)\n", myname); warnings++; } break; case 'm': /* select display mode */ if (strcmp(optarg, "io") == 0) { displaymode = DISP_IO; } else if (strcmp(optarg, "cpu") == 0) { displaymode = DISP_CPU; } else { fprintf(stderr, "%s: warning: `-m' option can only take args " "'io' or 'cpu'\n", myname); exit(1); } break; case 'o': /* select sort order */ order_name = optarg; break; case 't': ps.self = !ps.self; break; case 'C': ps.wcpu = !ps.wcpu; break; case 'H': ps.thread = !ps.thread; break; case 'T': ps.thread_id = !ps.thread_id; break; case 'j': ps.jail = !ps.jail; break; case 'J': /* display only jail's processes */ if ((ps.jid = jail_getid(optarg)) == -1) { fprintf(stderr, "%s: unknown jail\n", optarg); exit(1); } ps.jail = 1; break; case 'P': pcpu_stats = !pcpu_stats; break; case 'w': ps.swap = 1; break; case 'z': ps.kidle = !ps.kidle; break; default: fprintf(stderr, "Usage: %s [-abCHIijnPqStuvwz] [-d count] [-m io | cpu] [-o field] [-p pid]\n" " [-s time] [-J jail] [-U username] [number]\n", myname); exit(1); } } /* get count of top processes to display (if any) */ if (optind < ac) { if ((topn = atoiwi(av[optind])) == Invalid) { fprintf(stderr, "%s: warning: process display count should be non-negative -- using default\n", myname); warnings++; } else { topn_specified = true; } } /* tricky: remember old value of preset_argc & set preset_argc = 0 */ i = preset_argc; preset_argc = 0; /* repeat only if we really did the preset arguments */ } while (i != 0); /* set constants for username/uid display correctly */ if (!do_unames) { uname_field = " UID "; get_userid = itoa7; } /* initialize the kernel memory interface */ if (machine_init(&statics) == -1) { exit(1); } /* determine sorting order index, if necessary */ if (order_name != NULL) { if ((order_index = string_index(order_name, statics.order_names)) == -1) { const char * const *pp; fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n", myname, order_name); fprintf(stderr, "\tTry one of these:"); pp = statics.order_names; while (*pp != NULL) { fprintf(stderr, " %s", *pp++); } fputc('\n', stderr); exit(1); } } /* initialize termcap */ init_termcap(interactive); /* get the string to use for the process area header */ header_text = format_header(uname_field); /* initialize display interface */ if ((max_topn = display_init(&statics)) == -1) { fprintf(stderr, "%s: can't allocate sufficient memory\n", myname); exit(4); } /* print warning if user requested more processes than we can display */ if (topn > max_topn) { fprintf(stderr, "%s: warning: this terminal can only display %d processes.\n", myname, max_topn); warnings++; } /* adjust for topn == Infinity */ if (topn == Infinity) { /* * For smart terminals, infinity really means everything that can * be displayed, or Largest. * On dumb terminals, infinity means every process in the system! * We only really want to do that if it was explicitly specified. * This is always the case when "Default_TOPN != Infinity". But if * topn wasn't explicitly specified and we are on a dumb terminal * and the default is Infinity, then (and only then) we use * "Nominal_TOPN" instead. */ topn = smart_terminal ? Largest : (topn_specified ? Largest : Nominal_TOPN); } /* set header display accordingly */ display_header(topn > 0); /* determine interactive state */ if (interactive == 2) { interactive = smart_terminal; } /* if # of displays not specified, fill it in */ if (displays == 0) { displays = smart_terminal ? Infinity : 1; } /* hold interrupt signals while setting up the screen and the handlers */ old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP)); init_screen(); signal(SIGINT, leave); signal(SIGQUIT, leave); signal(SIGTSTP, tstop); signal(SIGWINCH, top_winch); sigsetmask(old_sigmask); if (warnings) { fputs("....", stderr); fflush(stderr); sleep(3 * warnings); fputc('\n', stderr); } restart: /* * main loop -- repeat while display count is positive or while it * indicates infinity (by being -1) */ while ((displays == -1) || (displays-- > 0)) { int (*compare)(const void * const, const void * const); /* get the current stats */ get_system_info(&system_info); compare = compares[order_index]; /* get the current set of processes */ processes = get_process_info(&system_info, &ps, compare); /* display the load averages */ (*d_loadave)(system_info.last_pid, system_info.load_avg); /* display the current time */ /* this method of getting the time SHOULD be fairly portable */ time(&curr_time); i_uptime(&system_info.boottime, &curr_time); i_timeofday(&curr_time); /* display process state breakdown */ (*d_procstates)(system_info.p_total, system_info.procstates); /* display the cpu state percentage breakdown */ if (dostates) /* but not the first time */ { (*d_cpustates)(system_info.cpustates); } else { /* we'll do it next time */ if (smart_terminal) { z_cpustates(); } else { putchar('\n'); } dostates = true; } /* display memory stats */ (*d_memory)(system_info.memory); (*d_arc)(system_info.arc); (*d_carc)(system_info.carc); /* display swap stats */ (*d_swap)(system_info.swap); /* handle message area */ (*d_message)(); /* update the header area */ (*d_header)(header_text); if (topn > 0) { /* determine number of processes to actually display */ /* this number will be the smallest of: active processes, number user requested, number current screen accomodates */ active_procs = system_info.p_pactive; if (active_procs > topn) { active_procs = topn; } if (active_procs > max_topn) { active_procs = max_topn; } /* now show the top "n" processes. */ for (i = 0; i < active_procs; i++) { (*d_process)(i, format_next_process(processes, get_userid, fmt_flags)); } } else { i = 0; } /* do end-screen processing */ u_endscreen(i); /* now, flush the output buffer */ if (fflush(stdout) != 0) { new_message(MT_standout, " Write error on stdout"); putchar('\r'); quit(1); } /* only do the rest if we have more displays to show */ if (displays) { /* switch out for new display on smart terminals */ if (smart_terminal) { if (overstrike) { reset_display(); } else { d_loadave = u_loadave; d_procstates = u_procstates; d_cpustates = u_cpustates; d_memory = u_memory; d_arc = u_arc; d_carc = u_carc; d_swap = u_swap; d_message = u_message; d_header = u_header; d_process = u_process; } } no_command = true; if (!interactive) { usleep(delay * 1e6); if (leaveflag) { end_screen(); exit(0); } } else while (no_command) { /* assume valid command unless told otherwise */ no_command = false; /* set up arguments for select with timeout */ FD_ZERO(&readfds); FD_SET(0, &readfds); /* for standard input */ timeout.tv_sec = delay; timeout.tv_usec = 0; if (leaveflag) { end_screen(); exit(0); } if (tstopflag) { /* move to the lower left */ end_screen(); fflush(stdout); /* default the signal handler action */ signal(SIGTSTP, SIG_DFL); /* unblock the signal and send ourselves one */ sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1))); kill(0, SIGTSTP); /* reset the signal handler */ signal(SIGTSTP, tstop); /* reinit screen */ reinit_screen(); reset_display(); tstopflag = 0; goto restart; } if (winchflag) { /* reascertain the screen dimensions */ get_screensize(); /* tell display to resize */ max_topn = display_resize(); /* reset the signal handler */ signal(SIGWINCH, top_winch); reset_display(); winchflag = 0; goto restart; } /* wait for either input or the end of the delay period */ sel_ret = select(2, &readfds, NULL, NULL, &timeout); if (sel_ret < 0 && errno != EINTR) quit(0); if (sel_ret > 0) { int newval; const char *errmsg; const struct command *cptr; /* something to read -- clear the message area first */ clear_message(); /* now read it and convert to command strchr */ /* (use "change" as a temporary to hold strchr) */ if (read(0, &ch, 1) != 1) { /* read error: either 0 or -1 */ new_message(MT_standout, " Read error on stdin"); putchar('\r'); quit(1); } if (ch == '\r' || ch == '\n') { continue; } cptr = all_commands; while (cptr->c != '\0') { if (cptr->c == ch) { break; } cptr++; } if (cptr->c == '\0') { new_message(MT_standout, " Command not understood"); putchar('\r'); no_command = true; } if (overstrike && !cptr->available_to_dumb) { new_message(MT_standout, " Command cannot be handled by this terminal"); putchar('\r'); no_command = true; } if (!no_command) { switch(cptr->id) { case CMD_redraw: /* redraw screen */ reset_display(); break; case CMD_update: /* merely update display */ /* is the load average high? */ if (system_info.load_avg[0] > LoadMax) { /* yes, go home for visual feedback */ go_home(); fflush(stdout); } break; case CMD_quit: quit(0); break; case CMD_help: reset_display(); top_clear(); show_help(); top_standout("Hit any key to continue: "); fflush(stdout); read(0, &ch, 1); break; case CMD_errors: /* show errors */ if (error_count() == 0) { new_message(MT_standout, " Currently no errors to report."); putchar('\r'); no_command = true; } else { reset_display(); top_clear(); show_errors(); top_standout("Hit any key to continue: "); fflush(stdout); read(0, &ch, 1); } break; case CMD_number: new_message(MT_standout, "Number of processes to show: "); newval = readline(tempbuf1, 8, true); if (newval > -1) { if (newval > max_topn) { new_message(MT_standout | MT_delayed, " This terminal can only display %d processes.", max_topn); putchar('\r'); } if (newval == 0) { /* inhibit the header */ display_header(false); } else if (newval > topn && topn == 0) { /* redraw the header */ display_header(true); d_header = i_header; } topn = newval; } break; case CMD_delay: /* new seconds delay */ new_message(MT_standout, "Seconds to delay: "); if ((i = readline(tempbuf1, 8, true)) > -1) { - if ((delay = i) == 0 && getuid() != 0) + if ((delay = i) == 0) { delay = 1; } } clear_message(); break; case CMD_displays: /* change display count */ new_message(MT_standout, "Displays to show (currently %s): ", displays == -1 ? "infinite" : itoa(displays)); if ((i = readline(tempbuf1, 10, true)) > 0) { displays = i; } else if (i == 0) { quit(0); } clear_message(); break; case CMD_kill: /* kill program */ new_message(0, "kill "); if (readline(tempbuf2, sizeof(tempbuf2), false) > 0) { if ((errmsg = kill_procs(tempbuf2)) != NULL) { new_message(MT_standout, "%s", errmsg); putchar('\r'); no_command = true; } } else { clear_message(); } break; case CMD_renice: /* renice program */ new_message(0, "renice "); if (readline(tempbuf2, sizeof(tempbuf2), false) > 0) { if ((errmsg = renice_procs(tempbuf2)) != NULL) { new_message(MT_standout, "%s", errmsg); putchar('\r'); no_command = true; } } else { clear_message(); } break; case CMD_idletog: ps.idle = !ps.idle; new_message(MT_standout | MT_delayed, " %sisplaying idle processes.", ps.idle ? "D" : "Not d"); putchar('\r'); break; case CMD_selftog: ps.self = !ps.self; new_message(MT_standout | MT_delayed, " %sisplaying self.", (ps.self) ? "D" : "Not d"); putchar('\r'); break; case CMD_user: if (handle_user(tempbuf2, sizeof(tempbuf2))) no_command = true; break; case CMD_thrtog: ps.thread = !ps.thread; new_message(MT_standout | MT_delayed, " Displaying threads %s", ps.thread ? "separately" : "as a count"); header_text = format_header(uname_field); reset_display(); putchar('\r'); break; case CMD_toggletid: ps.thread_id = !ps.thread_id; new_message(MT_standout | MT_delayed, " Displaying %s", ps.thread_id ? "tid" : "pid"); header_text = format_header(uname_field); reset_display(); putchar('\r'); break; case CMD_wcputog: ps.wcpu = !ps.wcpu; new_message(MT_standout | MT_delayed, " Displaying %s CPU", ps.wcpu ? "weighted" : "raw"); header_text = format_header(uname_field); reset_display(); putchar('\r'); break; case CMD_viewtog: - if (++displaymode == DISP_MAX) - displaymode = 0; + displaymode = displaymode == DISP_IO ? DISP_CPU : DISP_IO; header_text = format_header(uname_field); display_header(true); d_header = i_header; reset_display(); break; case CMD_viewsys: ps.system = !ps.system; break; case CMD_showargs: fmt_flags ^= FMT_SHOWARGS; break; case CMD_order: new_message(MT_standout, "Order to sort: "); if (readline(tempbuf2, sizeof(tempbuf2), false) > 0) { if ((i = string_index(tempbuf2, statics.order_names)) == -1) { new_message(MT_standout, " %s: unrecognized sorting order", tempbuf2); no_command = true; } else { order_index = i; } putchar('\r'); } else { clear_message(); } break; case CMD_jidtog: ps.jail = !ps.jail; new_message(MT_standout | MT_delayed, " %sisplaying jail ID.", ps.jail ? "D" : "Not d"); header_text = format_header(uname_field); reset_display(); putchar('\r'); break; case CMD_jail: new_message(MT_standout, "Jail to show (+ for all): "); if (readline(tempbuf2, sizeof(tempbuf2), false) > 0) { if (tempbuf2[0] == '+' && tempbuf2[1] == '\0') { ps.jid = -1; } else if ((i = jail_getid(tempbuf2)) == -1) { new_message(MT_standout, " %s: unknown jail", tempbuf2); no_command = true; } else { ps.jid = i; } if (ps.jail == 0) { ps.jail = 1; new_message(MT_standout | MT_delayed, " Displaying jail " "ID."); header_text = format_header(uname_field); reset_display(); } putchar('\r'); } else { clear_message(); } break; case CMD_kidletog: ps.kidle = !ps.kidle; new_message(MT_standout | MT_delayed, " %sisplaying system idle process.", ps.kidle ? "D" : "Not d"); putchar('\r'); break; case CMD_pcputog: pcpu_stats = !pcpu_stats; new_message(MT_standout | MT_delayed, " Displaying %sCPU statistics.", pcpu_stats ? "per-" : "global "); toggle_pcpustats(); max_topn = display_updatecpus(&statics); reset_display(); putchar('\r'); break; case CMD_swaptog: ps.swap = !ps.swap; new_message(MT_standout | MT_delayed, " %sisplaying per-process swap usage.", ps.swap ? "D" : "Not d"); header_text = format_header(uname_field); reset_display(); putchar('\r'); break; case CMD_pid: new_message(MT_standout, "Process id to show (+ for all): "); if (readline(tempbuf2, sizeof(tempbuf2), false) > 0) { if (tempbuf2[0] == '+' && tempbuf2[1] == '\0') { ps.pid = (pid_t)-1; } else { unsigned long long num; const char *errstr; num = strtonum(tempbuf2, 0, INT_MAX, &errstr); if (errstr != NULL || !find_pid(num)) { new_message(MT_standout, " %s: unknown pid", tempbuf2); no_command = true; } else { ps.pid = (pid_t)num; } } putchar('\r'); } else clear_message(); break; case CMD_NONE: assert("reached switch without command"); } } } /* flush out stuff that may have been written */ fflush(stdout); } } } #ifdef DEBUG fclose(debug); #endif quit(0); } /* * reset_display() - reset all the display routine pointers so that entire * screen will get redrawn. */ static void reset_display(void) { d_loadave = i_loadave; d_procstates = i_procstates; d_cpustates = i_cpustates; d_memory = i_memory; d_arc = i_arc; d_carc = i_carc; d_swap = i_swap; d_message = i_message; d_header = i_header; d_process = i_process; } /* * signal handlers */ static sigret_t leave(int i __unused) /* exit under normal conditions -- INT handler */ { leaveflag = 1; } static sigret_t tstop(int i __unused) /* SIGTSTP handler */ { tstopflag = 1; } static sigret_t top_winch(int i __unused) /* SIGWINCH handler */ { winchflag = 1; } void quit(int status) /* exit under duress */ { end_screen(); exit(status); } Index: head/usr.bin/top/top.h =================================================================== --- head/usr.bin/top/top.h (revision 334988) +++ head/usr.bin/top/top.h (revision 334989) @@ -1,73 +1,72 @@ /*- * Top - a top users display for Berkeley Unix * - * General (global) definitions * $FreeBSD$ */ #ifndef TOP_H #define TOP_H #include /* Number of lines of header information on the standard screen */ -extern int Header_lines; /* 7 */ +extern int Header_lines; /* Maximum number of columns allowed for display */ #define MAX_COLS 512 /* Special atoi routine returns either a non-negative number or one of: */ #define Infinity -1 #define Invalid -2 /* maximum number we can have */ #define Largest 0x7fffffff /* Exit code for system errors */ #define TOP_EX_SYS_ERROR 23 enum displaymodes { DISP_CPU = 0, DISP_IO, DISP_MAX }; /* * Format modifiers */ #define FMT_SHOWARGS 0x00000001 extern enum displaymodes displaymode; extern int pcpu_stats; extern int overstrike; extern pid_t mypid; extern const char * myname; extern int (*compares[])(const void*, const void*); const char* kill_procs(char *); const char* renice_procs(char *); extern char copyright[]; void quit(int); /* * The space command forces an immediate update. Sometimes, on loaded * systems, this update will take a significant period of time (because all * the output is buffered). So, if the short-term load average is above * "LoadMax", then top will put the cursor home immediately after the space * is pressed before the next update is attempted. This serves as a visual * acknowledgement of the command. */ #define LoadMax 5.0 /* * "Nominal_TOPN" is used as the default TOPN when * the output is a dumb terminal. If we didn't do this, then * we will get every * process in the system when running top on a dumb terminal (or redirected * to a file). Note that Nominal_TOPN is a default: it can still be * overridden on the command line, even with the value "infinity". */ #define Nominal_TOPN 18 #endif /* TOP_H */ Index: head/usr.bin/top/utils.c =================================================================== --- head/usr.bin/top/utils.c (revision 334988) +++ head/usr.bin/top/utils.c (revision 334989) @@ -1,407 +1,407 @@ /* * This program may be freely redistributed, * but this entire comment MUST remain intact. * * Copyright (c) 1984, 1989, William LeFebvre, Rice University * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University * * $FreeBSD$ */ /* * This file contains various handy utilities used by top. */ #include "top.h" #include "utils.h" #include #include #include #include #include #include #include #include #include int atoiwi(const char *str) { size_t len; len = strlen(str); if (len != 0) { if (strncmp(str, "infinity", len) == 0 || strncmp(str, "all", len) == 0 || strncmp(str, "maximum", len) == 0) { return(Infinity); } else if (str[0] == '-') { return(Invalid); } else { return(atoi(str)); } } return(0); } /* * itoa - convert integer (decimal) to ascii string for positive numbers * only (we don't bother with negative numbers since we know we * don't use them). */ /* * How do we know that 16 will suffice? * Because the biggest number that we will * ever convert will be 2^32-1, which is 10 * digits. */ _Static_assert(sizeof(int) <= 4, "buffer too small for this sized int"); char * itoa(unsigned int val) { char *ptr; static char buffer[16]; /* result is built here */ /* 16 is sufficient since the largest number we will ever convert will be 2^32-1, which is 10 digits. */ ptr = buffer + sizeof(buffer); *--ptr = '\0'; if (val == 0) { *--ptr = '0'; } else while (val != 0) { *--ptr = (val % 10) + '0'; val /= 10; } return(ptr); } /* * itoa7(val) - like itoa, except the number is right justified in a 7 * character field. This code is a duplication of itoa instead of * a front end to a more general routine for efficiency. */ char * itoa7(int val) { char *ptr; static char buffer[16]; /* result is built here */ /* 16 is sufficient since the largest number we will ever convert will be 2^32-1, which is 10 digits. */ ptr = buffer + sizeof(buffer); *--ptr = '\0'; if (val == 0) { *--ptr = '0'; } else while (val != 0) { *--ptr = (val % 10) + '0'; val /= 10; } while (ptr > buffer + sizeof(buffer) - 7) { *--ptr = ' '; } return(ptr); } /* * digits(val) - return number of decimal digits in val. Only works for - * non-negative numbers. If val <= 0 then digits(val) == 0. + * non-negative numbers. */ int __pure2 digits(int val) { int cnt = 0; if (val == 0) { return 1; } while (val > 0) { cnt++; val /= 10; } return(cnt); } /* * string_index(string, array) - find string in array and return index */ int string_index(const char *string, const char * const *array) { size_t i = 0; while (*array != NULL) { if (strcmp(string, *array) == 0) { return(i); } array++; i++; } return(-1); } /* * argparse(line, cntp) - parse arguments in string "line", separating them * out into an argv-like array, and setting *cntp to the number of * arguments encountered. This is a simple parser that doesn't understand * squat about quotes. */ const char * const * argparse(char *line, int *cntp) { const char **ap; static const char *argv[1024] = {0}; *cntp = 1; ap = &argv[1]; while ((*ap = strsep(&line, " ")) != NULL) { if (**ap != '\0') { (*cntp)++; if (*cntp >= (int)nitems(argv)) { break; } ap++; } } return (argv); } /* * percentages(cnt, out, new, old, diffs) - calculate percentage change * between array "old" and "new", putting the percentages i "out". * "cnt" is size of each array and "diffs" is used for scratch space. * The array "old" is updated on each call. * The routine assumes modulo arithmetic. This function is especially * useful on for calculating cpu state percentages. */ long percentages(int cnt, int *out, long *new, long *old, long *diffs) { int i; long change; long total_change; long *dp; long half_total; /* initialization */ total_change = 0; dp = diffs; /* calculate changes for each state and the overall change */ for (i = 0; i < cnt; i++) { if ((change = *new - *old) < 0) { /* this only happens when the counter wraps */ change = (int) ((unsigned long)*new-(unsigned long)*old); } total_change += (*dp++ = change); *old++ = *new++; } /* avoid divide by zero potential */ if (total_change == 0) { total_change = 1; } /* calculate percentages based on overall change, rounding up */ half_total = total_change / 2l; /* Do not divide by 0. Causes Floating point exception */ if(total_change) { for (i = 0; i < cnt; i++) { *out++ = (int)((*diffs++ * 1000 + half_total) / total_change); } } /* return the total in case the caller wants to use it */ return(total_change); } /* format_time(seconds) - format number of seconds into a suitable * display that will fit within 6 characters. Note that this * routine builds its string in a static area. If it needs * to be called more than once without overwriting previous data, * then we will need to adopt a technique similar to the * one used for format_k. */ /* Explanation: We want to keep the output within 6 characters. For low values we use the format mm:ss. For values that exceed 999:59, we switch to a format that displays hours and fractions: hhh.tH. For values that exceed 999.9, we use hhhh.t and drop the "H" designator. For values that exceed 9999.9, we use "???". */ char * format_time(long seconds) { static char result[10]; /* sanity protection */ if (seconds < 0 || seconds > (99999l * 360l)) { strcpy(result, " ???"); } else if (seconds >= (1000l * 60l)) { /* alternate (slow) method displaying hours and tenths */ sprintf(result, "%5.1fH", (double)seconds / (double)(60l * 60l)); /* It is possible that the sprintf took more than 6 characters. If so, then the "H" appears as result[6]. If not, then there is a \0 in result[6]. Either way, it is safe to step on. */ result[6] = '\0'; } else { /* standard method produces MMM:SS */ /* we avoid printf as must as possible to make this quick */ sprintf(result, "%3ld:%02ld", (long)(seconds / 60), (long)(seconds % 60)); } return(result); } /* * format_k(amt) - format a kilobyte memory value, returning a string * suitable for display. Returns a pointer to a static * area that changes each call. "amt" is converted to a * string with a trailing "K". If "amt" is 10000 or greater, * then it is formatted as megabytes (rounded) with a * trailing "M". */ /* * Compromise time. We need to return a string, but we don't want the * caller to have to worry about freeing a dynamically allocated string. * Unfortunately, we can't just return a pointer to a static area as one * of the common uses of this function is in a large call to sprintf where * it might get invoked several times. Our compromise is to maintain an * array of strings and cycle thru them with each invocation. We make the * array large enough to handle the above mentioned case. The constant * NUM_STRINGS defines the number of strings in this array: we can tolerate * up to NUM_STRINGS calls before we start overwriting old information. * Keeping NUM_STRINGS a power of two will allow an intelligent optimizer * to convert the modulo operation into something quicker. What a hack! */ #define NUM_STRINGS 8 char * -format_k(int amt) +format_k(long amt) { static char retarray[NUM_STRINGS][16]; static int index = 0; char *p; char *ret; char tag = 'K'; p = ret = retarray[index]; index = (index + 1) % NUM_STRINGS; if (amt >= 10000) { amt = (amt + 512) / 1024; tag = 'M'; if (amt >= 10000) { amt = (amt + 512) / 1024; tag = 'G'; } } p = stpcpy(p, itoa(amt)); *p++ = tag; *p = '\0'; return(ret); } char * format_k2(unsigned long long amt) { static char retarray[NUM_STRINGS][16]; static int index = 0; char *p; char *ret; char tag = 'K'; p = ret = retarray[index]; index = (index + 1) % NUM_STRINGS; if (amt >= 100000) { amt = (amt + 512) / 1024; tag = 'M'; if (amt >= 100000) { amt = (amt + 512) / 1024; tag = 'G'; } } p = stpcpy(p, itoa((int)amt)); *p++ = tag; *p = '\0'; return(ret); } int find_pid(pid_t pid) { kvm_t *kd = NULL; struct kinfo_proc *pbase = NULL; int nproc; int ret = 0; kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL); if (kd == NULL) { fprintf(stderr, "top: kvm_open() failed.\n"); quit(TOP_EX_SYS_ERROR); } pbase = kvm_getprocs(kd, KERN_PROC_PID, pid, &nproc); if (pbase == NULL) { goto done; } if ((nproc == 1) && (pbase->ki_pid == pid)) { ret = 1; } done: kvm_close(kd); return ret; } Index: head/usr.bin/top/utils.h =================================================================== --- head/usr.bin/top/utils.h (revision 334988) +++ head/usr.bin/top/utils.h (revision 334989) @@ -1,26 +1,26 @@ /* * $FreeBSD$ * * Top users/processes display for Unix * * This program may be freely redistributed, * but this entire comment MUST remain intact. * * Copyright (c) 1984, 1989, William LeFebvre, Rice University * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University */ #include int atoiwi(const char *); char *itoa(unsigned int); char *itoa7(int); int digits(int); const char * const *argparse(char *, int *); long percentages(int, int *, long *, long *, long *); char *format_time(long); -char *format_k(int); +char *format_k(long); char *format_k2(unsigned long long); int string_index(const char *string, const char * const *array); int find_pid(pid_t pid);