Index: head/usr.bin/top/display.c =================================================================== --- head/usr.bin/top/display.c (revision 338188) +++ head/usr.bin/top/display.c (revision 338189) @@ -1,1360 +1,1359 @@ /* * Top users/processes display for Unix * Version 3 * * 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 display information on the screen. * Each section of the screen has two routines: one for initially writing * all constant and dynamic text, and one for only updating the text that * changes. The prefix "i_" is used on all the "initial" routines and the * prefix "u_" is used for all the "updating" routines. * * ASSUMPTIONS: * None of the "i_" routines use any of the termcap capabilities. * In this way, those routines can be safely used on terminals that * have minimal (or nonexistant) terminal capabilities. * * The routines are called in this order: *_loadave, i_timeofday, * *_procstates, *_cpustates, *_memory, *_message, *_header, * *_process, u_endscreen. */ #include #include #include #include #include +#include #include #include #include #include #include #include #include #include #include "screen.h" /* interface to screen package */ #include "layout.h" /* defines for screen position layout */ #include "display.h" #include "top.h" #include "machine.h" /* we should eliminate this!!! */ #include "utils.h" #ifdef DEBUG FILE *debug; #endif static int lmpid = 0; static int last_hi = 0; /* used in u_process and u_endscreen */ static int lastline = 0; #define lineindex(l) ((l)*screen_width) /* things initialized by display_init and used thruout */ /* buffer of proc information lines for display updating */ static char *screenbuf = NULL; static const char * const *procstate_names; static const char * const *cpustate_names; static const char * const *memory_names; static const char * const *arc_names; static const char * const *carc_names; static const char * const *swap_names; static int num_procstates; static int num_cpustates; static int num_memory; static int num_swap; static int *lprocstates; static int *lcpustates; static int *lmemory; static int *lswap; static int num_cpus; static int *cpustate_columns; static int cpustate_total_length; static int cpustates_column; static enum { OFF, ON, ERASE } header_status = ON; static void summary_format(char *, int *, const char * const *); static void line_update(char *, char *, int, int); static int setup_buffer_bufsiz = 0; static char * setup_buffer(char *, int); int x_lastpid = 10; int y_lastpid = 0; int x_loadave = 33; int x_loadave_nompid = 15; int y_loadave = 0; int x_procstate = 0; int y_procstate = 1; int x_brkdn = 15; int y_brkdn = 1; int x_mem = 5; int y_mem = 3; int x_arc = 5; int y_arc = 4; int x_carc = 5; int y_carc = 5; int x_swap = 6; int y_swap = 4; int y_message = 5; int x_header = 0; int y_header = 6; int x_idlecursor = 0; int y_idlecursor = 5; int y_procs = 7; int y_cpustates = 2; int Header_lines = 7; int display_resize(void) { int lines; /* first, deallocate any previous buffer that may have been there */ if (screenbuf != NULL) { free(screenbuf); } /* calculate the current dimensions */ /* if operating in "dumb" mode, we only need one line */ lines = smart_terminal ? screen_length - Header_lines : 1; if (lines < 0) lines = 0; /* now, allocate space for the screen buffer */ screenbuf = calloc(lines, screen_width); if (screenbuf == NULL) { /* oops! */ return(-1); } /* return number of lines available */ /* for dumb terminals, pretend like we can show any amount */ return(smart_terminal ? lines : Largest); } int display_updatecpus(struct statics *statics) { int lines; int i; /* call resize to do the dirty work */ lines = display_resize(); if (pcpu_stats) num_cpus = statics->ncpus; else num_cpus = 1; cpustates_column = 5; /* CPU: */ if (num_cpus > 1) { cpustates_column += 1 + digits(num_cpus); /* CPU #: */ } /* fill the "last" array with all -1s, to insure correct updating */ for (i = 0; i < num_cpustates * num_cpus; ++i) { lcpustates[i] = -1; } return(lines); } int display_init(struct statics * statics) { int lines; char **pp; int *ip; int i; lines = display_updatecpus(statics); /* only do the rest if we need to */ if (lines > -1) { /* save pointers and allocate space for names */ procstate_names = statics->procstate_names; num_procstates = 8; assert(num_procstates > 0); lprocstates = calloc(num_procstates, sizeof(int)); cpustate_names = statics->cpustate_names; swap_names = statics->swap_names; num_swap = 7; assert(num_swap > 0); lswap = calloc(num_swap, sizeof(int)); num_cpustates = CPUSTATES; assert(num_cpustates > 0); lcpustates = calloc(num_cpustates * sizeof(int), statics->ncpus); cpustate_columns = calloc(num_cpustates, sizeof(int)); memory_names = statics->memory_names; num_memory = 7; assert(num_memory > 0); lmemory = calloc(num_memory, sizeof(int)); arc_names = statics->arc_names; carc_names = statics->carc_names; /* calculate starting columns where needed */ cpustate_total_length = 0; pp = cpustate_names; ip = cpustate_columns; while (*pp != NULL) { *ip++ = cpustate_total_length; if ((i = strlen(*pp++)) > 0) { cpustate_total_length += i + 8; } } } /* return number of lines available */ return(lines); } void i_loadave(int mpid, double avenrun[]) { int i; /* i_loadave also clears the screen, since it is first */ top_clear(); /* mpid == -1 implies this system doesn't have an _mpid */ if (mpid != -1) { printf("last pid: %5d; ", mpid); } printf("load averages"); for (i = 0; i < 3; i++) { printf("%c %5.2f", i == 0 ? ':' : ',', avenrun[i]); } lmpid = mpid; } void u_loadave(int mpid, double *avenrun) { int i; if (mpid != -1) { /* change screen only when value has really changed */ if (mpid != lmpid) { Move_to(x_lastpid, y_lastpid); printf("%5d", mpid); lmpid = mpid; } /* i remembers x coordinate to move to */ i = x_loadave; } else { i = x_loadave_nompid; } /* move into position for load averages */ Move_to(i, y_loadave); /* display new load averages */ /* we should optimize this and only display changes */ for (i = 0; i < 3; i++) { printf("%s%5.2f", i == 0 ? "" : ", ", avenrun[i]); } } void i_timeofday(time_t *tod) { /* * Display the current time. * "ctime" always returns a string that looks like this: * * Sun Sep 16 01:03:52 1973 * 012345678901234567890123 * 1 2 * * We want indices 11 thru 18 (length 8). */ if (smart_terminal) { Move_to(screen_width - 8, 0); } else { fputs(" ", stdout); } #ifdef DEBUG { char *foo; foo = ctime(tod); fputs(foo, stdout); } #endif printf("%-8.8s\n", &(ctime(tod)[11])); lastline = 1; } static int ltotal = 0; static char *procstates_buffer = NULL; /* * *_procstates(total, brkdn, names) - print the process summary line * * Assumptions: cursor is at the beginning of the line on entry * lastline is valid */ void i_procstates(int total, int *brkdn) { int i; procstates_buffer = setup_buffer(procstates_buffer, 0); /* write current number of processes and remember the value */ printf("%d %s:", total, ps.thread ? "threads" : "processes"); ltotal = total; /* put out enough spaces to get to column 15 */ i = digits(total); while (i++ < (ps.thread ? 6 : 4)) { putchar(' '); } /* format and print the process state summary */ summary_format(procstates_buffer, brkdn, procstate_names); fputs(procstates_buffer, stdout); /* save the numbers for next time */ memcpy(lprocstates, brkdn, num_procstates * sizeof(int)); } void u_procstates(int total, int *brkdn) { static char *new = NULL; int i; new = setup_buffer(new, 0); /* update number of processes only if it has changed */ if (ltotal != total) { /* move and overwrite */ if (x_procstate == 0) { Move_to(x_procstate, y_procstate); } else { /* cursor is already there...no motion needed */ assert(lastline == 1); } printf("%d", total); /* if number of digits differs, rewrite the label */ if (digits(total) != digits(ltotal)) { printf(" %s:", ps.thread ? "threads" : "processes"); /* put out enough spaces to get to column 15 */ i = digits(total); while (i++ < (ps.thread ? 6 : 4)) { putchar(' '); } /* cursor may end up right where we want it!!! */ } /* save new total */ ltotal = total; } /* see if any of the state numbers has changed */ if (memcmp(lprocstates, brkdn, num_procstates * sizeof(int)) != 0) { /* format and update the line */ summary_format(new, brkdn, procstate_names); line_update(procstates_buffer, new, x_brkdn, y_brkdn); memcpy(lprocstates, brkdn, num_procstates * sizeof(int)); } } void i_cpustates(int *states) { int i = 0; int value; const char * const *names; const char *thisname; int *hstates = states; int cpu; for (cpu = 0; cpu < num_cpus; cpu++) { names = cpustate_names; /* print tag and bump lastline */ if (num_cpus == 1) printf("\nCPU: "); else { value = printf("\nCPU %d: ", cpu); while (value++ <= cpustates_column) printf(" "); } lastline++; /* now walk thru the names and print the line */ while ((thisname = *names++) != NULL) { if (*thisname != '\0') { /* retrieve the value and remember it */ value = *states++; /* if percentage is >= 1000, print it as 100% */ printf((value >= 1000 ? "%s%4.0f%% %s" : "%s%4.1f%% %s"), (i++ % num_cpustates) == 0 ? "" : ", ", ((float)value)/10., thisname); } } } /* copy over values into "last" array */ states = hstates; memcpy(lcpustates, states, num_cpustates * sizeof(int) * num_cpus); } void u_cpustates(int *states) { int value; const char * const *names; const char *thisname; int *hstates = states; int *lp; int *colp; int cpu; for (cpu = 0; cpu < num_cpus; cpu++) { names = cpustate_names; Move_to(cpustates_column, y_cpustates + cpu); lastline = y_cpustates + cpu; lp = lcpustates + (cpu * num_cpustates); colp = cpustate_columns; /* we could be much more optimal about this */ while ((thisname = *names++) != NULL) { if (*thisname != '\0') { /* did the value change since last time? */ if (*lp != *states) { /* yes, move and change */ Move_to(cpustates_column + *colp, y_cpustates + cpu); lastline = y_cpustates + cpu; /* retrieve value and remember it */ value = *states; /* if percentage is >= 1000, print it as 100% */ printf((value >= 1000 ? "%4.0f" : "%4.1f"), ((double)value)/10.); /* remember it for next time */ *lp = value; } } /* increment and move on */ lp++; states++; colp++; } } states = hstates; } void z_cpustates(void) { int i = 0; const char **names; char *thisname; int cpu, value; for (cpu = 0; cpu < num_cpus; cpu++) { names = cpustate_names; /* show tag and bump lastline */ if (num_cpus == 1) printf("\nCPU: "); else { value = printf("\nCPU %d: ", cpu); while (value++ <= cpustates_column) printf(" "); } lastline++; while ((thisname = *names++) != NULL) { if (*thisname != '\0') { printf("%s %% %s", (i++ % num_cpustates) == 0 ? "" : ", ", thisname); } } } /* fill the "last" array with all -1s, to insure correct updating */ for (i = 0; i < num_cpustates * num_cpus; ++i) { lcpustates[i] = -1; } } /* * *_memory(stats) - print "Memory: " followed by the memory summary string * * Assumptions: cursor is on "lastline" * for i_memory ONLY: cursor is on the previous line */ static char *memory_buffer = NULL; void i_memory(int *stats) { memory_buffer = setup_buffer(memory_buffer, 0); fputs("\nMem: ", stdout); lastline++; /* format and print the memory summary */ summary_format(memory_buffer, stats, memory_names); fputs(memory_buffer, stdout); } void u_memory(int *stats) { static char *new = NULL; new = setup_buffer(new, 0); /* format the new line */ summary_format(new, stats, memory_names); line_update(memory_buffer, new, x_mem, y_mem); } /* * *_arc(stats) - print "ARC: " followed by the ARC summary string * * Assumptions: cursor is on "lastline" * for i_arc ONLY: cursor is on the previous line */ static char *arc_buffer = NULL; void i_arc(int *stats) { arc_buffer = setup_buffer(arc_buffer, 0); if (arc_names == NULL) return; fputs("\nARC: ", stdout); lastline++; /* format and print the memory summary */ summary_format(arc_buffer, stats, arc_names); fputs(arc_buffer, stdout); } void u_arc(int *stats) { static char *new = NULL; new = setup_buffer(new, 0); if (arc_names == NULL) return; /* format the new line */ summary_format(new, stats, arc_names); line_update(arc_buffer, new, x_arc, y_arc); } /* * *_carc(stats) - print "Compressed ARC: " followed by the summary string * * Assumptions: cursor is on "lastline" * for i_carc ONLY: cursor is on the previous line */ static char *carc_buffer = NULL; void i_carc(int *stats) { carc_buffer = setup_buffer(carc_buffer, 0); if (carc_names == NULL) return; fputs("\n ", stdout); lastline++; /* format and print the memory summary */ summary_format(carc_buffer, stats, carc_names); fputs(carc_buffer, stdout); } void u_carc(int *stats) { static char *new = NULL; new = setup_buffer(new, 0); if (carc_names == NULL) return; /* format the new line */ summary_format(new, stats, carc_names); line_update(carc_buffer, new, x_carc, y_carc); } /* * *_swap(stats) - print "Swap: " followed by the swap summary string * * Assumptions: cursor is on "lastline" * for i_swap ONLY: cursor is on the previous line */ static char *swap_buffer = NULL; void i_swap(int *stats) { swap_buffer = setup_buffer(swap_buffer, 0); fputs("\nSwap: ", stdout); lastline++; /* format and print the swap summary */ summary_format(swap_buffer, stats, swap_names); fputs(swap_buffer, stdout); } void u_swap(int *stats) { static char *new = NULL; new = setup_buffer(new, 0); /* format the new line */ summary_format(new, stats, swap_names); line_update(swap_buffer, new, x_swap, y_swap); } /* * *_message() - print the next pending message line, or erase the one * that is there. * * Note that u_message is (currently) the same as i_message. * * Assumptions: lastline is consistent */ /* * i_message is funny because it gets its message asynchronously (with * respect to screen updates). */ #define NEXT_MSG_ADDLEN 5 static char *next_msg = NULL; static int msglen = 0; /* Invariant: msglen is always the length of the message currently displayed on the screen (even when next_msg doesn't contain that message). */ void i_message(void) { next_msg = setup_buffer(next_msg, NEXT_MSG_ADDLEN); while (lastline < y_message) { fputc('\n', stdout); lastline++; } if (next_msg[0] != '\0') { top_standout(next_msg); msglen = strlen(next_msg); next_msg[0] = '\0'; } else if (msglen > 0) { (void) clear_eol(msglen); msglen = 0; } } void u_message(void) { i_message(); } static int header_length; /* * Trim a header string to the current display width and return a newly * allocated area with the trimmed header. */ const char * trim_header(const char *text) { char *s; int width; s = NULL; width = screen_width; header_length = strlen(text); if (header_length >= width) { s = strndup(text, width); if (s == NULL) return (NULL); } return (s); } /* * *_header(text) - print the header for the process area * * Assumptions: cursor is on the previous line and lastline is consistent */ void i_header(const char *text) { char *s; s = trim_header(text); if (s != NULL) text = s; if (header_status == ON) { putchar('\n'); fputs(text, stdout); lastline++; } else if (header_status == ERASE) { header_status = OFF; } free(s); } void u_header(const char *text __unused) { if (header_status == ERASE) { putchar('\n'); lastline++; clear_eol(header_length); header_status = OFF; } } /* * *_process(line, thisline) - print one process line * * Assumptions: lastline is consistent */ void i_process(int line, char *thisline) { char *p; char *base; /* make sure we are on the correct line */ while (lastline < y_procs + line) { putchar('\n'); lastline++; } /* truncate the line to conform to our current screen width */ thisline[screen_width] = '\0'; /* write the line out */ fputs(thisline, stdout); /* copy it in to our buffer */ base = smart_terminal ? screenbuf + lineindex(line) : screenbuf; p = stpcpy(base, thisline); /* zero fill the rest of it */ memset(p, 0, screen_width - (p - base)); } void u_process(int line, char *newline) { char *optr; int screen_line = line + Header_lines; char *bufferline; /* remember a pointer to the current line in the screen buffer */ bufferline = &screenbuf[lineindex(line)]; /* truncate the line to conform to our current screen width */ newline[screen_width] = '\0'; /* is line higher than we went on the last display? */ if (line >= last_hi) { /* yes, just ignore screenbuf and write it out directly */ /* get positioned on the correct line */ if (screen_line - lastline == 1) { putchar('\n'); lastline++; } else { Move_to(0, screen_line); lastline = screen_line; } /* now write the line */ fputs(newline, stdout); /* copy it in to the buffer */ optr = stpcpy(bufferline, newline); /* zero fill the rest of it */ memset(optr, 0, screen_width - (optr - bufferline)); } else { line_update(bufferline, newline, 0, line + Header_lines); } } void u_endscreen(int hi) { int screen_line = hi + Header_lines; int i; if (smart_terminal) { if (hi < last_hi) { /* need to blank the remainder of the screen */ /* but only if there is any screen left below this line */ if (lastline + 1 < screen_length) { /* efficiently move to the end of currently displayed info */ if (screen_line - lastline < 5) { while (lastline < screen_line) { putchar('\n'); lastline++; } } else { Move_to(0, screen_line); lastline = screen_line; } if (clear_to_end) { /* we can do this the easy way */ putcap(clear_to_end); } else { /* use clear_eol on each line */ i = hi; while ((void) clear_eol(strlen(&screenbuf[lineindex(i++)])), i < last_hi) { putchar('\n'); } } } } last_hi = hi; /* move the cursor to a pleasant place */ Move_to(x_idlecursor, y_idlecursor); lastline = y_idlecursor; } else { /* separate this display from the next with some vertical room */ fputs("\n\n", stdout); } } void display_header(int t) { if (t) { header_status = ON; } else if (header_status == ON) { header_status = ERASE; } } void new_message(int type, const char *msgfmt, ...) { va_list args; size_t i; va_start(args, msgfmt); /* first, format the message */ vsnprintf(next_msg, setup_buffer_bufsiz + NEXT_MSG_ADDLEN, msgfmt, args); va_end(args); if (msglen > 0) { /* message there already -- can we clear it? */ if (!overstrike) { /* yes -- write it and clear to end */ i = strlen(next_msg); if ((type & MT_delayed) == 0) { if (type & MT_standout) { top_standout(next_msg); } else { fputs(next_msg, stdout); } clear_eol(msglen - i); msglen = i; next_msg[0] = '\0'; } } } else { if ((type & MT_delayed) == 0) { if (type & MT_standout) { top_standout(next_msg); } else { fputs(next_msg, stdout); } msglen = strlen(next_msg); next_msg[0] = '\0'; } } } void clear_message(void) { if (clear_eol(msglen) == 1) { putchar('\r'); } } int readline(char *buffer, int size, int numeric) { char *ptr = buffer; char ch; char cnt = 0; char maxcnt = 0; /* allow room for null terminator */ size -= 1; /* read loop */ while ((fflush(stdout), read(0, ptr, 1) > 0)) { /* newline means we are done */ if ((ch = *ptr) == '\n' || ch == '\r') { break; } /* handle special editing characters */ if (ch == ch_kill) { /* kill line -- account for overstriking */ if (overstrike) { msglen += maxcnt; } /* return null string */ *buffer = '\0'; putchar('\r'); return(-1); } else if (ch == ch_erase) { /* erase previous character */ if (cnt <= 0) { /* none to erase! */ putchar('\7'); } else { fputs("\b \b", stdout); ptr--; cnt--; } } /* check for character validity and buffer overflow */ else if (cnt == size || (numeric && !isdigit(ch)) || !isprint(ch)) { /* not legal */ putchar('\7'); } else { /* echo it and store it in the buffer */ putchar(ch); ptr++; cnt++; if (cnt > maxcnt) { maxcnt = cnt; } } } /* all done -- null terminate the string */ *ptr = '\0'; /* account for the extra characters in the message area */ /* (if terminal overstrikes, remember the furthest they went) */ msglen += overstrike ? maxcnt : cnt; /* return either inputted number or string length */ putchar('\r'); return(cnt == 0 ? -1 : numeric ? atoi(buffer) : cnt); } /* internal support routines */ static void summary_format(char *str, int *numbers, const char * const *names) { char *p; int num; const char *thisname; char rbuf[6]; /* format each number followed by its string */ p = str; while ((thisname = *names++) != NULL) { /* get the number to format */ num = *numbers++; /* display only non-zero numbers */ if (num > 0) { /* is this number in kilobytes? */ if (thisname[0] == 'K') { /* yes: format it as a memory value */ p = stpcpy(p, format_k(num)); /* skip over the K, since it was included by format_k */ p = stpcpy(p, thisname+1); } /* is this number a ratio? */ else if (thisname[0] == ':') { (void) snprintf(rbuf, sizeof(rbuf), "%.2f", (float)*(numbers - 2) / (float)num); p = stpcpy(p, rbuf); p = stpcpy(p, thisname); } else { p = stpcpy(p, itoa(num)); p = stpcpy(p, thisname); } } /* ignore negative numbers, but display corresponding string */ else if (num < 0) { p = stpcpy(p, thisname); } } /* if the last two characters in the string are ", ", delete them */ p -= 2; if (p >= str && p[0] == ',' && p[1] == ' ') { *p = '\0'; } } static void line_update(char *old, char *new, int start, int line) { int ch; int diff; int newcol = start + 1; int lastcol = start; char cursor_on_line = false; char *current; /* compare the two strings and only rewrite what has changed */ current = old; #ifdef DEBUG fprintf(debug, "line_update, starting at %d\n", start); fputs(old, debug); fputc('\n', debug); fputs(new, debug); fputs("\n-\n", debug); #endif /* start things off on the right foot */ /* this is to make sure the invariants get set up right */ if ((ch = *new++) != *old) { if (line - lastline == 1 && start == 0) { putchar('\n'); } else { Move_to(start, line); } cursor_on_line = true; putchar(ch); *old = ch; lastcol = 1; } old++; /* * main loop -- check each character. If the old and new aren't the * same, then update the display. When the distance from the * current cursor position to the new change is small enough, * the characters that belong there are written to move the * cursor over. * * Invariants: * lastcol is the column where the cursor currently is sitting * (always one beyond the end of the last mismatch). */ do /* yes, a do...while */ { if ((ch = *new++) != *old) { /* new character is different from old */ /* make sure the cursor is on top of this character */ diff = newcol - lastcol; if (diff > 0) { /* some motion is required--figure out which is shorter */ if (diff < 6 && cursor_on_line) { /* overwrite old stuff--get it out of the old buffer */ printf("%.*s", diff, ¤t[lastcol-start]); } else { /* use cursor addressing */ Move_to(newcol, line); cursor_on_line = true; } /* remember where the cursor is */ lastcol = newcol + 1; } else { /* already there, update position */ lastcol++; } /* write what we need to */ if (ch == '\0') { /* at the end--terminate with a clear-to-end-of-line */ (void) clear_eol(strlen(old)); } else { /* write the new character */ putchar(ch); } /* put the new character in the screen buffer */ *old = ch; } /* update working column and screen buffer pointer */ newcol++; old++; } while (ch != '\0'); /* zero out the rest of the line buffer -- MUST BE DONE! */ diff = screen_width - newcol; if (diff > 0) { memset(old, 0, diff); } /* remember where the current line is */ if (cursor_on_line) { lastline = line; } } /* * printable(str) - make the string pointed to by "str" into one that is * printable (i.e.: all ascii), by converting all non-printable * characters into '?'. Replacements are done in place and a pointer * to the original buffer is returned. */ char * printable(char str[]) { char *ptr; char ch; ptr = str; while ((ch = *ptr) != '\0') { if (!isprint(ch)) { *ptr = '?'; } ptr++; } return(str); } void i_uptime(struct timeval *bt, time_t *tod) { time_t uptime; int days, hrs, mins, secs; if (bt->tv_sec != -1) { uptime = *tod - bt->tv_sec; days = uptime / 86400; uptime %= 86400; hrs = uptime / 3600; uptime %= 3600; mins = uptime / 60; secs = uptime % 60; /* * Display the uptime. */ if (smart_terminal) { Move_to((screen_width - 24) - (days > 9 ? 1 : 0), 0); } else { fputs(" ", stdout); } printf(" up %d+%02d:%02d:%02d", days, hrs, mins, secs); } } #define SETUPBUFFER_REQUIRED_ADDBUFSIZ 2 static char * setup_buffer(char *buffer, int addlen) { char *b = NULL; if (NULL == buffer) { setup_buffer_bufsiz = screen_width; b = calloc(setup_buffer_bufsiz + addlen + SETUPBUFFER_REQUIRED_ADDBUFSIZ, sizeof(char)); } else { if (screen_width > setup_buffer_bufsiz) { setup_buffer_bufsiz = screen_width; free(buffer); b = calloc(setup_buffer_bufsiz + addlen + SETUPBUFFER_REQUIRED_ADDBUFSIZ, sizeof(char)); } else { b = buffer; } } if (NULL == b) { - fprintf(stderr, "%s: can't allocate sufficient memory\n", - myname); - exit(4); + errx(4, "can't allocate sufficient memory"); } return b; } Index: head/usr.bin/top/screen.c =================================================================== --- head/usr.bin/top/screen.c (revision 338188) +++ head/usr.bin/top/screen.c (revision 338189) @@ -1,317 +1,318 @@ /* * Top users/processes display for Unix * Version 3 * * 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 interface to termcap and stty/gtty. * * Paul Vixie, February 1987: converted to use ioctl() instead of stty/gtty. * * I put in code to turn on the TOSTOP bit while top was running, but I * didn't really like the results. If you desire it, turn on the * preprocessor variable "TOStop". --wnl */ #include + +#include #include #include #include #include #include #include #include "screen.h" #include "top.h" int overstrike; int screen_length; int screen_width; char ch_erase; char ch_kill; char smart_terminal; static char termcap_buf[1024]; static char string_buffer[1024]; static char home[15]; static char lower_left[15]; char *clear_line; static char *clear_screen; char *clear_to_end; char *cursor_motion; static char *start_standout; static char *end_standout; static char *terminal_init; static char *terminal_end; static struct termios old_settings; static struct termios new_settings; static char is_a_terminal = false; #define NON_INTERACTIVE_MODE_VIRTUAL_SCREEN_WIDTH 1024 void init_termcap(bool interactive) { char *bufptr; char *PCptr; char *term_name; int status; screen_width = 0; screen_length = 0; if (!interactive) { /* pretend we have a dumb terminal */ screen_width = NON_INTERACTIVE_MODE_VIRTUAL_SCREEN_WIDTH; smart_terminal = false; return; } /* assume we have a smart terminal until proven otherwise */ smart_terminal = true; /* get the terminal name */ term_name = getenv("TERM"); /* if there is no TERM, assume it's a dumb terminal */ /* patch courtesy of Sam Horrocks at telegraph.ics.uci.edu */ if (term_name == NULL) { smart_terminal = false; return; } /* now get the termcap entry */ if ((status = tgetent(termcap_buf, term_name)) != 1) { if (status == -1) { - fprintf(stderr, "%s: can't open termcap file\n", myname); + warnx("can't open termcap file"); } else { - fprintf(stderr, "%s: no termcap entry for a `%s' terminal\n", - myname, term_name); + warnx("no termcap entry for a `%s' terminal", term_name); } /* pretend it's dumb and proceed */ smart_terminal = false; return; } /* "hardcopy" immediately indicates a very stupid terminal */ if (tgetflag("hc")) { smart_terminal = false; return; } /* set up common terminal capabilities */ if ((screen_length = tgetnum("li")) <= 0) { screen_length = smart_terminal = 0; return; } /* screen_width is a little different */ if ((screen_width = tgetnum("co")) == -1) { screen_width = 79; } else { screen_width -= 1; } /* terminals that overstrike need special attention */ overstrike = tgetflag("os"); /* initialize the pointer into the termcap string buffer */ bufptr = string_buffer; /* get "ce", clear to end */ if (!overstrike) { clear_line = tgetstr("ce", &bufptr); } /* get necessary capabilities */ if ((clear_screen = tgetstr("cl", &bufptr)) == NULL || (cursor_motion = tgetstr("cm", &bufptr)) == NULL) { smart_terminal = false; return; } /* get some more sophisticated stuff -- these are optional */ clear_to_end = tgetstr("cd", &bufptr); terminal_init = tgetstr("ti", &bufptr); terminal_end = tgetstr("te", &bufptr); start_standout = tgetstr("so", &bufptr); end_standout = tgetstr("se", &bufptr); /* pad character */ PC = (PCptr = tgetstr("pc", &bufptr)) ? *PCptr : 0; /* set convenience strings */ strncpy(home, tgoto(cursor_motion, 0, 0), sizeof(home) - 1); home[sizeof(home) - 1] = '\0'; /* (lower_left is set in get_screensize) */ /* get the actual screen size with an ioctl, if needed */ /* This may change screen_width and screen_length, and it always sets lower_left. */ get_screensize(); /* if stdout is not a terminal, pretend we are a dumb terminal */ if (tcgetattr(STDOUT_FILENO, &old_settings) == -1) { smart_terminal = false; } } void init_screen(void) { /* get the old settings for safe keeping */ if (tcgetattr(STDOUT_FILENO, &old_settings) != -1) { /* copy the settings so we can modify them */ new_settings = old_settings; /* turn off ICANON, character echo and tab expansion */ new_settings.c_lflag &= ~(ICANON|ECHO); new_settings.c_oflag &= ~(TAB3); new_settings.c_cc[VMIN] = 1; new_settings.c_cc[VTIME] = 0; tcsetattr(STDOUT_FILENO, TCSADRAIN, &new_settings); /* remember the erase and kill characters */ ch_erase = old_settings.c_cc[VERASE]; ch_kill = old_settings.c_cc[VKILL]; /* remember that it really is a terminal */ is_a_terminal = true; /* send the termcap initialization string */ putcap(terminal_init); } if (!is_a_terminal) { /* not a terminal at all---consider it dumb */ smart_terminal = false; } } void end_screen(void) { /* move to the lower left, clear the line and send "te" */ if (smart_terminal) { putcap(lower_left); putcap(clear_line); fflush(stdout); putcap(terminal_end); } /* if we have settings to reset, then do so */ if (is_a_terminal) { tcsetattr(STDOUT_FILENO, TCSADRAIN, &old_settings); } } void reinit_screen(void) { /* install our settings if it is a terminal */ if (is_a_terminal) { tcsetattr(STDOUT_FILENO, TCSADRAIN, &new_settings); } /* send init string */ if (smart_terminal) { putcap(terminal_init); } } void get_screensize(void) { struct winsize ws; if (ioctl (1, TIOCGWINSZ, &ws) != -1) { if (ws.ws_row != 0) { screen_length = ws.ws_row; } if (ws.ws_col != 0) { screen_width = ws.ws_col - 1; } } (void) strncpy(lower_left, tgoto(cursor_motion, 0, screen_length - 1), sizeof(lower_left) - 1); lower_left[sizeof(lower_left) - 1] = '\0'; } void top_standout(const char *msg) { if (smart_terminal) { putcap(start_standout); fputs(msg, stdout); putcap(end_standout); } else { fputs(msg, stdout); } } void top_clear(void) { if (smart_terminal) { putcap(clear_screen); } } int clear_eol(int len) { if (smart_terminal && !overstrike && len > 0) { if (clear_line) { putcap(clear_line); return(0); } else { while (len-- > 0) { putchar(' '); } return(1); } } return(-1); } Index: head/usr.bin/top/top.c =================================================================== --- head/usr.bin/top/top.c (revision 338188) +++ head/usr.bin/top/top.c (revision 338189) @@ -1,1220 +1,1188 @@ /*- * 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 #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]; 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]; sigset_t old_sigmask, new_sigmask; 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 = NULL; int ac = -1; 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; char *nptr; /* 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 = true; 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; + errx(0, "version FreeBSD"); + 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); + errx(1, "%s: unknown user\n", optarg); } 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); + warnx("warning: display count should be positive -- option ignored"); 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, &nptr); if (nptr == optarg) { warnx("warning: invalid delay"); delay = 2; warnings++; } if (delay < 0) { - fprintf(stderr, - "%s: warning: seconds delay should be positive -- using default\n", - myname); + warnx("warning: seconds delay should be positive -- using default"); 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); + warnx("warning: `-q' option failed (%m)"); 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); + errx(1, "warning: `-m' option can only take args 'io' or 'cpu'"); } 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); + errx(1, +"[-abCHIijnPqStuvwz] [-d count] [-m io | cpu] [-o field] [-p pid]\n" +" [-s time] [-J jail] [-U username] [number]"); } } /* 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++; + warnx("warning: process display count should be non-negative -- using default"); + 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); + warnx("'%s' is not a recognized sorting order.", 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); + errx(4, "can't allocate sufficient memory"); } /* 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++; + warnx("warning: this terminal can only display %d processes.", 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 */ sigemptyset(&new_sigmask); sigaddset(&new_sigmask, SIGINT); sigaddset(&new_sigmask, SIGQUIT); sigaddset(&new_sigmask, SIGTSTP); sigprocmask(SIG_BLOCK, &new_sigmask, &old_sigmask); init_screen(); signal(SIGINT, leave); signal(SIGQUIT, leave); signal(SIGTSTP, tstop); signal(SIGWINCH, top_winch); sigprocmask(SIG_SETMASK, &old_sigmask, NULL); 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); (*d_cpustates)(system_info.cpustates); /* 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 */ 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) { 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: 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(false && "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 __dead2 quit(int status) /* exit under duress */ { end_screen(); exit(status); } Index: head/usr.bin/top/top.h =================================================================== --- head/usr.bin/top/top.h (revision 338188) +++ head/usr.bin/top/top.h (revision 338189) @@ -1,69 +1,67 @@ /*- * Top - a top users display for Berkeley Unix * * $FreeBSD$ */ #ifndef TOP_H #define TOP_H #include /* Number of lines of header information on the standard screen */ extern int Header_lines; /* 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 */