2 * Copyright (c) 1984 through 2008, William LeFebvre
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following disclaimer
13 * in the documentation and/or other materials provided with the
16 * * Neither the name of William LeFebvre nor the names of other
17 * contributors may be used to endorse or promote products derived from
18 * this software without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 * Top users/processes display for Unix
39 * This file contains the routines that implement some of the interactive
40 * mode commands. Note that some of the commands are implemented in-line
41 * in "main". This is necessary because they change the global state of
42 * "top" (i.e.: changing the number of processes to display).
52 #ifdef HAVE_SYS_RESOURCE_H
53 #include <sys/resource.h>
56 #if defined(HAVE_DECL_SYS_SIGLIST) & defined(HAVE_STRCASECMP)
57 #define USE_SYS_SIGLIST
60 #ifdef USE_SYS_SIGLIST
61 extern const char * const sys_siglist[];
62 extern const char * const sys_signame[];
64 #include "sigdesc.h" /* generated automatically */
68 #include "globalstate.h"
80 extern char *copyright;
82 typedef struct command {
84 int (*cmd_func)(globalstate *);
89 * Some of the commands make system calls that could generate errors.
90 * These errors are collected up in an array of structures for later
91 * contemplation and display. Such routines return a string containing an
92 * error message, or NULL if no errors occurred. We need an upper limit on
93 * the number of errors, so we arbitrarily choose 20.
98 struct errs /* structure for a system-call error */
100 int errnum; /* value of errno (that is, the actual error) */
101 char *arg; /* argument that caused the error */
104 static struct errs errs[ERRMAX];
107 /* These macros get used to reset and log the errors */
108 #define ERR_RESET errcnt = 0
109 #define ERROR(p, e) if (errcnt < ERRMAX) \
111 errs[errcnt].arg = (p); \
112 errs[errcnt++].errnum = (e); \
116 * err_compar(p1, p2) - comparison routine used by "qsort"
117 * for sorting errors.
121 err_compar(const void *p1, const void *p2)
126 if ((result = ((struct errs *)p1)->errnum -
127 ((struct errs *)p2)->errnum) == 0)
129 return(strcmp(((struct errs *)p1)->arg,
130 ((struct errs *)p2)->arg));
136 * str_adderr(str, len, err) - add an explanation of error "err" to
137 * the string "str" without overflowing length "len". return
138 * number of characters remaining in str, or 0 if overflowed.
142 str_adderr(char *str, int len, int err)
148 msg = err == 0 ? "Not a number" : errmsg(err);
149 msglen = strlen(msg) + 2;
154 (void) strcat(str, ": ");
155 (void) strcat(str, msg);
156 return(len - msglen);
160 * str_addarg(str, len, arg, first) - add the string argument "arg" to
161 * the string "str" without overflowing length "len". This is the
162 * first in the group when "first" is set (indicating that a comma
163 * should NOT be added to the front). Return number of characters
164 * remaining in str, or 0 if overflowed.
168 str_addarg(char *str, int len, char *arg, int first)
173 arglen = strlen(arg);
184 (void) strcat(str, ", ");
186 (void) strcat(str, arg);
187 return(len - arglen);
193 * Use message_error to log errors in the errs array. This function
194 * will combine identical errors to make the message short, but if
195 * there is more than one type of error it will call message_error
205 register struct errs *errp;
206 register int cnt = 0;
207 register int first = Yes;
208 register int currerr = -1;
209 int stringlen = 0; /* characters still available in "string" */
212 /* if there are no errors, our job is easy */
218 /* sort the errors */
219 qsort((char *)errs, errcnt, sizeof(struct errs), err_compar);
221 /* initialize the buffer (probably not necessary) */
223 stringlen = STRMAX - 1;
225 /* loop thru the sorted list, logging errors */
228 /* point to the current error */
229 errp = &(errs[cnt++]);
231 /* note that on overflow "stringlen" will become 0 and all
232 subsequent calls to str_addarg or str_adderr will return 0 */
234 /* if the error number is different then add the error string */
235 if (errp->errnum != currerr)
239 /* add error string and log the error */
240 stringlen = str_adderr(string, stringlen, currerr);
241 message_error(" %s", string);
244 /* reset the buffer */
246 stringlen = STRMAX - 1;
248 /* move to next error num */
249 currerr = errp->errnum;
254 stringlen = str_addarg(string, stringlen, errp->arg, first);
258 /* add final message */
259 stringlen = str_adderr(string, stringlen, currerr);
261 /* write the error string */
262 message_error(" %s", string);
266 * Utility routines that help with some of the commands.
270 next_field(char *str)
274 if ((str = strchr(str, ' ')) == NULL)
279 while (*++str == ' ') /* loop */;
281 /* if there is nothing left of the string, return NULL */
282 /* This fix is dedicated to Greg Earle */
283 return(*str == '\0' ? NULL : str);
287 scanint(char *str, int *intp)
290 register int val = 0;
293 /* if there is nothing left of the string, flag it as an error */
294 /* This fix is dedicated to Greg Earle */
300 while ((ch = *str++) != '\0')
304 val = val * 10 + (ch - '0');
306 else if (isspace(ch))
320 * error_count() - return the number of errors currently logged.
331 * show_errors() - display on stdout the current log of errors.
338 register int cnt = 0;
339 register struct errs *errp = errs;
341 printf("%d error%s:\n\n", errcnt, errcnt == 1 ? "" : "s");
342 while (cnt++ < errcnt)
344 printf("%5s: %s\n", errp->arg,
345 errp->errnum == 0 ? "Not a number" : errmsg(errp->errnum));
351 * kill_procs(str) - send signals to processes, much like the "kill"
352 * command does; invoked in response to 'k'.
356 kill_procs(char *str)
360 int signum = SIGTERM; /* default */
364 #ifndef USE_SYS_SIGLIST
365 struct sigdesc *sigp;
368 /* reset error array */
371 /* remember our uid */
374 /* skip over leading white space */
375 while (isspace((int)*str)) str++;
379 /* explicit signal specified */
380 if ((nptr = next_field(str)) == NULL)
382 message_error(" kill: no processes specified");
387 if (isdigit((int)str[0]))
389 (void) scanint(str, &signum);
390 if (signum <= 0 || signum >= NSIG)
392 message_error(" kill: invalid signal number");
398 /* translate the name into a number */
399 #ifdef USE_SYS_SIGLIST
400 for (signum = 1; signum < NSIG; signum++)
402 if (strcasecmp(sys_signame[signum], str) == 0)
409 message_error(" kill: bad signal name");
413 for (sigp = sigdesc; sigp->name != NULL; sigp++)
415 #ifdef HAVE_STRCASECMP
416 if (strcasecmp(sigp->name, str) == 0)
418 if (strcmp(sigp->name, str) == 0)
421 signum = sigp->number;
426 /* was it ever found */
427 if (sigp->name == NULL)
429 message_error(" kill: bad signal name");
434 /* put the new pointer in place */
438 /* loop thru the string, killing processes */
441 if (scanint(str, &procnum) == -1)
447 /* check process owner if we're not root */
448 owner = proc_owner(procnum);
449 if (uid && (uid != owner))
451 ERROR(str, owner == -1 ? ESRCH : EACCES);
453 /* go in for the kill */
454 else if (kill(procnum, signum) == -1)
456 /* chalk up an error */
460 } while ((str = next_field(str)) != NULL);
467 * renice_procs(str) - change the "nice" of processes, much like the
468 * "renice" command does; invoked in response to 'r'.
472 renice_procs(char *str)
475 register char negate;
483 /* allow for negative priority values */
484 if ((negate = (*str == '-')) != 0)
486 /* move past the minus sign */
490 /* use procnum as a temporary holding place and get the number */
491 procnum = scanint(str, &prio);
493 /* negate if necessary */
499 #if defined(PRIO_MIN) && defined(PRIO_MAX)
500 /* check for validity */
501 if (procnum == -1 || prio < PRIO_MIN || prio > PRIO_MAX)
503 message_error(" renice: bad priority value");
507 /* move to the first process number */
508 if ((str = next_field(str)) == NULL)
510 message_error(" remice: no processes specified");
514 #ifdef HAVE_SETPRIORITY
515 /* loop thru the process numbers, renicing each one */
518 if (scanint(str, &procnum) == -1)
523 /* check process owner if we're not root */
524 else if (uid && (uid != proc_owner(procnum)))
528 else if (setpriority(PRIO_PROCESS, procnum, prio) == -1)
532 } while ((str = next_field(str)) != NULL);
535 message_error(" renice operation not supported");
539 /* COMMAND ROUTINES */
542 * Each command routine is called by command_process and is passed a
543 * pointer to the current global state. Command routines are free
544 * to change anything in the global state, although changes to the
545 * statics structure are discouraged. Whatever a command routine
546 * returns will be returned by command_process.
550 cmd_quit(globalstate *gstate)
558 cmd_update(globalstate *gstate)
561 /* go home for visual feedback */
569 cmd_redraw(globalstate *gstate)
572 gstate->fulldraw = Yes;
577 cmd_color(globalstate *gstate)
580 gstate->use_color = color_activate(-1);
581 gstate->fulldraw = Yes;
586 cmd_number(globalstate *gstate)
592 message_prompt("Number of processes to show: ");
593 newval = readline(tmpbuf, 8, Yes);
596 if (newval > gstate->max_topn)
598 message_error(" This terminal can only display %d processes",
604 /* inhibit the header */
608 else if (gstate->topn == 0)
613 gstate->topn = newval;
619 cmd_delay(globalstate *gstate)
625 message_prompt("Seconds to delay: ");
626 if ((newval = readline(tmpbuf, 8, Yes)) > -1)
628 if ((gstate->delay = newval) == 0 && getuid() != 0)
637 cmd_idle(globalstate *gstate)
640 gstate->pselect.idle = !gstate->pselect.idle;
641 message_error(" %sisplaying idle processes.",
642 gstate->pselect.idle ? "D" : "Not d");
647 cmd_displays(globalstate *gstate)
653 message_prompt("Displays to show (currently %s): ",
654 gstate->displays == -1 ? "infinite" :
655 itoa(gstate->displays));
657 if ((i = readline(tmpbuf, 10, Yes)) > 0)
659 gstate->displays = i;
670 cmd_cmdline(globalstate *gstate)
673 if (gstate->statics->flags.fullcmds)
675 gstate->pselect.fullcmd = !gstate->pselect.fullcmd;
676 message_error(" %sisplaying full command lines.",
677 gstate->pselect.fullcmd ? "D" : "Not d");
680 message_error(" Full command display not supported.");
685 cmd_order(globalstate *gstate)
688 char tmpbuf[MAX_COLS];
691 if (gstate->statics->order_names != NULL)
693 message_prompt("Column to sort: ");
694 if (readline(tmpbuf, sizeof(tmpbuf), No) > 0)
696 if ((i = string_index(tmpbuf, gstate->statics->order_names)) == -1)
698 message_error(" Sort order \"%s\" not recognized", tmpbuf);
702 gstate->order_index = i;
711 cmd_order_x(globalstate *gstate, char *name, ...)
719 names = gstate->statics->order_names;
722 if ((i = string_index(name, names)) == -1)
724 /* check the alternate list */
726 p = va_arg(ap, char *);
729 if ((i = string_index(p, names)) != -1)
731 gstate->order_index = i;
734 p = va_arg(ap, char *);
736 message_error(" Sort order not recognized");
740 gstate->order_index = i;
748 cmd_order_cpu(globalstate *gstate)
751 return cmd_order_x(gstate, "cpu", NULL);
755 cmd_order_pid(globalstate *gstate)
758 return cmd_order_x(gstate, "pid", NULL);
762 cmd_order_mem(globalstate *gstate)
765 return cmd_order_x(gstate, "mem", "size", NULL);
769 cmd_order_time(globalstate *gstate)
772 return cmd_order_x(gstate, "time");
778 cmd_kill(globalstate *gstate)
781 char tmpbuf[MAX_COLS];
783 message_prompt_plain("kill ");
784 if (readline(tmpbuf, sizeof(tmpbuf), No) > 0)
792 cmd_renice(globalstate *gstate)
795 char tmpbuf[MAX_COLS];
797 message_prompt_plain("renice ");
798 if (readline(tmpbuf, sizeof(tmpbuf), No) > 0)
800 renice_procs(tmpbuf);
808 cmd_user(globalstate *gstate)
811 char linebuf[MAX_COLS];
815 message_prompt("Username to show: ");
816 if (readline(linebuf, sizeof(linebuf), No) > 0)
818 if (linebuf[0] == '+' &&
821 gstate->pselect.uid = -1;
824 else if ((i = userid(linebuf)) == -1)
826 message_error(" %s: unknown user", linebuf);
830 gstate->pselect.uid = i;
838 cmd_command(globalstate *gstate)
841 char linebuf[MAX_COLS];
843 if (gstate->pselect.command != NULL)
845 free(gstate->pselect.command);
846 gstate->pselect.command = NULL;
849 message_prompt("Command to show: ");
850 if (readline(linebuf, sizeof(linebuf), No) > 0)
852 if (linebuf[0] != '\0')
854 gstate->pselect.command = strdup(linebuf);
861 cmd_useruid(globalstate *gstate)
864 gstate->pselect.usernames = !gstate->pselect.usernames;
870 cmd_mode(globalstate *gstate)
873 if (gstate->statics->modemax <= 1)
877 gstate->pselect.mode = (gstate->pselect.mode + 1) % gstate->statics->modemax;
883 cmd_system(globalstate *gstate)
886 gstate->pselect.system = !gstate->pselect.system;
892 cmd_threads(globalstate *gstate)
895 if (gstate->statics->flags.threads)
897 gstate->pselect.threads = !gstate->pselect.threads;
904 /* forward reference for cmd_help, as it needs to see the command_table */
905 int cmd_help(globalstate *gstate);
908 command command_table[] = {
909 { '\014', cmd_redraw, "redraw screen" },
910 { ' ', cmd_update, "update screen" },
911 { '?', cmd_help, "help; show this text" },
912 { 'h', cmd_help, NULL },
913 { 'C', cmd_color, "toggle the use of color" },
914 { 'H', cmd_threads, "toggle the display of individual threads" },
915 { 't', cmd_threads, NULL },
916 { 'M', cmd_order_mem, "sort by memory usage" },
917 { 'N', cmd_order_pid, "sort by process id" },
918 { 'P', cmd_order_cpu, "sort by CPU usage" },
919 { 'S', cmd_system, "toggle the display of system processes" },
920 { 'T', cmd_order_time, "sort by CPU time" },
921 { 'U', cmd_useruid, "toggle the display of usernames or uids" },
922 { 'c', cmd_command, "display processes by command name" },
923 { 'd', cmd_displays, "change number of displays to show" },
924 { 'f', cmd_cmdline, "toggle the display of full command paths" },
925 { 'i', cmd_idle, "toggle the displaying of idle processes" },
926 { 'I', cmd_idle, NULL },
928 { 'k', cmd_kill, "kill processes; send a signal to a list of processes" },
930 { 'm', cmd_mode, "toggle between display modes" },
931 { 'n', cmd_number, "change number of processes to display" },
932 { '#', cmd_number, NULL },
933 { 'o', cmd_order, "specify sort order (see below)" },
934 { 'q', (int (*)(globalstate *))cmd_quit, "quit" },
936 { 'r', cmd_renice, "renice a process" },
938 { 's', cmd_delay, "change number of seconds to delay between updates" },
939 { 'u', cmd_user, "display processes for only one user (+ selects all users)" },
940 { '\0', NULL, NULL },
944 cmd_help(globalstate *gstate)
952 display_pagerstart();
954 display_pager("Top version %s, %s\n", version_string(), copyright);
955 display_pager("Platform module: %s\n\n", MODULE);
956 display_pager("A top users display for Unix\n\n");
957 display_pager("These single-character commands are available:\n\n");
960 while (c->cmd_func != NULL)
962 /* skip null help strings */
963 if ((help = c->help) == NULL)
968 /* translate character in to something readable */
972 buf[1] = c->ch + '@';
975 else if (c->ch == ' ')
985 /* if the next command is the same, fold them onto one line */
986 if ((c+1)->cmd_func == c->cmd_func)
989 p = buf + strlen(buf);
995 display_pager("%-7s - %s\n", buf, help);
999 display_pager("\nNot all commands are available on all systems.\n\n");
1000 display_pager("Available sort orders: %s\n", gstate->order_namelist);
1002 gstate->fulldraw = Yes;
1007 * int command_process(globalstate *gstate, int cmd)
1009 * Process the single-character command "cmd". The global state may
1010 * be modified by the command to alter the output. Returns CMD_ERROR
1011 * if there was a serious error that requires an immediate exit, CMD_OK
1012 * to indicate success, CMD_REFRESH to indicate that the screen needs
1013 * to be refreshed immediately, CMD_UNKNOWN when the command is not known,
1014 * and CMD_NA when the command is not available. Error messages for
1015 * CMD_NA and CMD_UNKNOWN must be handled by the caller.
1019 command_process(globalstate *gstate, int cmd)
1025 while (c->cmd_func != NULL)
1029 return (c->cmd_func)(gstate);