]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/top/commands.c
top(1): Use standard boolean rather than homegrown alternative
[FreeBSD/FreeBSD.git] / usr.bin / top / commands.c
1 /*
2  *  Top users/processes display for Unix
3  *
4  *  This program may be freely redistributed,
5  *  but this entire comment MUST remain intact.
6  *
7  *  Copyright (c) 1984, 1989, William LeFebvre, Rice University
8  *  Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University
9  *
10  * $FreeBSD$
11  */
12
13 /*
14  *  This file contains the routines that implement some of the interactive
15  *  mode commands.  Note that some of the commands are implemented in-line
16  *  in "main".  This is necessary because they change the global state of
17  *  "top" (i.e.:  changing the number of processes to display).
18  */
19
20 #include <sys/resource.h>
21
22 #include <ctype.h>
23 #include <errno.h>
24 #include <signal.h>
25 #include <stdbool.h>
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <unistd.h>
30
31 #include "commands.h"
32 #include "sigdesc.h"            /* generated automatically */
33 #include "top.h"
34 #include "machine.h"
35
36 static int err_compar(const void *p1, const void *p2);
37
38 struct errs             /* structure for a system-call error */
39 {
40     int  errnum;        /* value of errno (that is, the actual error) */
41     char *arg;          /* argument that caused the error */
42 };
43
44 static char *err_string(void);
45 static int str_adderr(char *str, int len, int err);
46 static int str_addarg(char *str, int len, char *arg, int first);
47
48 /*
49  *  show_help() - display the help screen; invoked in response to
50  *              either 'h' or '?'.
51  */
52
53 void
54 show_help(void)
55 {
56     printf("Top version FreeBSD, %s\n", copyright);
57     fputs("\n\n\
58 A top users display for Unix\n\
59 \n\
60 These single-character commands are available:\n\
61 \n\
62 ^L      - redraw screen\n\
63 q       - quit\n\
64 h or ?  - help; show this text\n", stdout);
65
66     /* not all commands are availalbe with overstrike terminals */
67     if (overstrike)
68     {
69         fputs("\n\
70 Other commands are also available, but this terminal is not\n\
71 sophisticated enough to handle those commands gracefully.\n\n", stdout);
72     }
73     else
74     {
75         fputs("\
76 C       - toggle the displaying of weighted CPU percentage\n\
77 d       - change number of displays to show\n\
78 e       - list errors generated by last \"kill\" or \"renice\" command\n\
79 H       - toggle the displaying of threads\n\
80 i or I  - toggle the displaying of idle processes\n\
81 j       - toggle the displaying of jail ID\n\
82 J       - display processes for only one jail (+ selects all jails)\n\
83 k       - kill processes; send a signal to a list of processes\n\
84 m       - toggle the display between 'cpu' and 'io' modes\n\
85 n or #  - change number of processes to display\n", stdout);
86         if (displaymode == DISP_CPU)
87                 fputs("\
88 o       - specify sort order (pri, size, res, cpu, time, threads, jid, pid)\n",
89             stdout);
90         else
91                 fputs("\
92 o       - specify sort order (vcsw, ivcsw, read, write, fault, total, jid, pid)\n",
93             stdout);
94         fputs("\
95 P       - toggle the displaying of per-CPU statistics\n\
96 r       - renice a process\n\
97 s       - change number of seconds to delay between updates\n\
98 S       - toggle the displaying of system processes\n\
99 a       - toggle the displaying of process titles\n\
100 t       - toggle the display of this process\n\
101 u       - display processes for only one user (+ selects all users)\n\
102 w       - toggle the display of swap use for each process\n\
103 z       - toggle the displaying of the system idle process\n\
104 \n\
105 \n", stdout);
106     }
107 }
108
109 /*
110  *  Utility routines that help with some of the commands.
111  */
112
113 static char *
114 next_field(char *str)
115 {
116     if ((str = strchr(str, ' ')) == NULL)
117     {
118         return(NULL);
119     }
120     *str = '\0';
121     while (*++str == ' ') /* loop */;
122
123     /* if there is nothing left of the string, return NULL */
124     /* This fix is dedicated to Greg Earle */
125     return(*str == '\0' ? NULL : str);
126 }
127
128 static int
129 scanint(char *str, int *intp)
130 {
131     int val = 0;
132     char ch;
133
134     /* if there is nothing left of the string, flag it as an error */
135     /* This fix is dedicated to Greg Earle */
136     if (*str == '\0')
137     {
138         return(-1);
139     }
140
141     while ((ch = *str++) != '\0')
142     {
143         if (isdigit(ch))
144         {
145             val = val * 10 + (ch - '0');
146         }
147         else if (isspace(ch))
148         {
149             break;
150         }
151         else
152         {
153             return(-1);
154         }
155     }
156     *intp = val;
157     return(0);
158 }
159
160 /*
161  *  Some of the commands make system calls that could generate errors.
162  *  These errors are collected up in an array of structures for later
163  *  contemplation and display.  Such routines return a string containing an
164  *  error message, or NULL if no errors occurred.  The next few routines are
165  *  for manipulating and displaying these errors.  We need an upper limit on
166  *  the number of errors, so we arbitrarily choose 20.
167  */
168
169 #define ERRMAX 20
170
171 static struct errs errs[ERRMAX];
172 static int errcnt;
173 static char err_toomany[] = " too many errors occurred";
174 static char err_listem[] = 
175         " Many errors occurred.  Press `e' to display the list of errors.";
176
177 /* These macros get used to reset and log the errors */
178 #define ERR_RESET   errcnt = 0
179 #define ERROR(p, e) if (errcnt >= ERRMAX) \
180                     { \
181                         return(err_toomany); \
182                     } \
183                     else \
184                     { \
185                         errs[errcnt].arg = (p); \
186                         errs[errcnt++].errnum = (e); \
187                     }
188
189 /*
190  *  err_string() - return an appropriate error string.  This is what the
191  *      command will return for displaying.  If no errors were logged, then
192  *      return NULL.  The maximum length of the error string is defined by
193  *      "STRMAX".
194  */
195
196 #define STRMAX 80
197
198 char *err_string(void)
199 {
200     struct errs *errp;
201     int  cnt = 0;
202     int  first = true;
203     int  currerr = -1;
204     int stringlen;              /* characters still available in "string" */
205     static char string[STRMAX];
206
207     /* if there are no errors, return NULL */
208     if (errcnt == 0)
209     {
210         return(NULL);
211     }
212
213     /* sort the errors */
214     qsort((char *)errs, errcnt, sizeof(struct errs), err_compar);
215
216     /* need a space at the front of the error string */
217     string[0] = ' ';
218     string[1] = '\0';
219     stringlen = STRMAX - 2;
220
221     /* loop thru the sorted list, building an error string */
222     while (cnt < errcnt)
223     {
224         errp = &(errs[cnt++]);
225         if (errp->errnum != currerr)
226         {
227             if (currerr != -1)
228             {
229                 if ((stringlen = str_adderr(string, stringlen, currerr)) < 2)
230                 {
231                     return(err_listem);
232                 }
233                 strcat(string, "; ");     /* we know there's more */
234             }
235             currerr = errp->errnum;
236             first = true;
237         }
238         if ((stringlen = str_addarg(string, stringlen, errp->arg, first)) ==0)
239         {
240             return(err_listem);
241         }
242         first = false;
243     }
244
245     /* add final message */
246     stringlen = str_adderr(string, stringlen, currerr);
247
248     /* return the error string */
249     return(stringlen == 0 ? err_listem : string);
250 }
251
252 /*
253  *  str_adderr(str, len, err) - add an explanation of error "err" to
254  *      the string "str".
255  */
256
257 static int
258 str_adderr(char *str, int len, int err)
259 {
260     const char *msg;
261     int msglen;
262
263     msg = err == 0 ? "Not a number" : strerror(err);
264     msglen = strlen(msg) + 2;
265     if (len <= msglen)
266     {
267         return(0);
268     }
269     strcat(str, ": ");
270     strcat(str, msg);
271     return(len - msglen);
272 }
273
274 /*
275  *  str_addarg(str, len, arg, first) - add the string argument "arg" to
276  *      the string "str".  This is the first in the group when "first"
277  *      is set (indicating that a comma should NOT be added to the front).
278  */
279
280 static int
281 str_addarg(char str[], int len, char arg[], int first)
282 {
283     int arglen;
284
285     arglen = strlen(arg);
286     if (!first)
287     {
288         arglen += 2;
289     }
290     if (len <= arglen)
291     {
292         return(0);
293     }
294     if (!first)
295     {
296         strcat(str, ", ");
297     }
298     strcat(str, arg);
299     return(len - arglen);
300 }
301
302 /*
303  *  err_compar(p1, p2) - comparison routine used by "qsort"
304  *      for sorting errors.
305  */
306
307 static int
308 err_compar(const void *p1, const void *p2)
309 {
310     int result;
311     const struct errs * const g1 = (const struct errs * const)p1;
312     const struct errs * const g2 = (const struct errs * const)p2;
313
314
315
316     if ((result = g1->errnum - g2->errnum) == 0)
317     {
318         return(strcmp(g1->arg, g2->arg));
319     }
320     return(result);
321 }
322
323 /*
324  *  error_count() - return the number of errors currently logged.
325  */
326
327 int
328 error_count(void)
329 {
330     return(errcnt);
331 }
332
333 /*
334  *  show_errors() - display on stdout the current log of errors.
335  */
336
337 void
338 show_errors(void)
339 {
340     int cnt = 0;
341     struct errs *errp = errs;
342
343     printf("%d error%s:\n\n", errcnt, errcnt == 1 ? "" : "s");
344     while (cnt++ < errcnt)
345     {
346         printf("%5s: %s\n", errp->arg,
347             errp->errnum == 0 ? "Not a number" : strerror(errp->errnum));
348         errp++;
349     }
350 }
351
352 static char no_proc_specified[] = " no processes specified";
353 static char invalid_signal_number[] = " invalid_signal_number";
354 static char bad_signal_name[] = " bad signal name";
355 static char bad_pri_value[] = " bad priority value";
356
357 /*
358  *  kill_procs(str) - send signals to processes, much like the "kill"
359  *              command does; invoked in response to 'k'.
360  */
361
362 char *
363 kill_procs(char *str)
364 {
365     char *nptr;
366     int signum = SIGTERM;       /* default */
367     int procnum;
368     struct sigdesc *sigp;
369     int uid;
370
371     /* reset error array */
372     ERR_RESET;
373
374     /* remember our uid */
375     uid = getuid();
376
377     /* skip over leading white space */
378     while (isspace(*str)) str++;
379
380     if (str[0] == '-')
381     {
382         /* explicit signal specified */
383         if ((nptr = next_field(str)) == NULL)
384         {
385             return(no_proc_specified);
386         }
387
388         if (isdigit(str[1]))
389         {
390             scanint(str + 1, &signum);
391             if (signum <= 0 || signum >= NSIG)
392             {
393                 return(invalid_signal_number);
394             }
395         }
396         else 
397         {
398             /* translate the name into a number */
399             for (sigp = sigdesc; sigp->name != NULL; sigp++)
400             {
401                 if (strcmp(sigp->name, str + 1) == 0)
402                 {
403                     signum = sigp->number;
404                     break;
405                 }
406             }
407
408             /* was it ever found */
409             if (sigp->name == NULL)
410             {
411                 return(bad_signal_name);
412             }
413         }
414         /* put the new pointer in place */
415         str = nptr;
416     }
417
418     /* loop thru the string, killing processes */
419     do
420     {
421         if (scanint(str, &procnum) == -1)
422         {
423             ERROR(str, 0);
424         }
425         else
426         {
427             /* check process owner if we're not root */
428             if (uid && (uid != proc_owner(procnum)))
429             {
430                 ERROR(str, EACCES);
431             }
432             /* go in for the kill */
433             else if (kill(procnum, signum) == -1)
434             {
435                 /* chalk up an error */
436                 ERROR(str, errno);
437             }
438         }
439     } while ((str = next_field(str)) != NULL);
440
441     /* return appropriate error string */
442     return(err_string());
443 }
444
445 /*
446  *  renice_procs(str) - change the "nice" of processes, much like the
447  *              "renice" command does; invoked in response to 'r'.
448  */
449
450 char *
451 renice_procs(char *str)
452 {
453     char negate;
454     int prio;
455     int procnum;
456     int uid;
457
458     ERR_RESET;
459     uid = getuid();
460
461     /* allow for negative priority values */
462     if ((negate = (*str == '-')) != 0)
463     {
464         /* move past the minus sign */
465         str++;
466     }
467
468     /* use procnum as a temporary holding place and get the number */
469     procnum = scanint(str, &prio);
470
471     /* negate if necessary */
472     if (negate)
473     {
474         prio = -prio;
475     }
476
477     /* check for validity */
478     if (procnum == -1 || prio < PRIO_MIN || prio > PRIO_MAX)
479     {
480         return(bad_pri_value);
481     }
482
483     /* move to the first process number */
484     if ((str = next_field(str)) == NULL)
485     {
486         return(no_proc_specified);
487     }
488
489     /* loop thru the process numbers, renicing each one */
490     do
491     {
492         if (scanint(str, &procnum) == -1)
493         {
494             ERROR(str, 0);
495         }
496
497         /* check process owner if we're not root */
498         else if (uid && (uid != proc_owner(procnum)))
499         {
500             ERROR(str, EACCES);
501         }
502         else if (setpriority(PRIO_PROCESS, procnum, prio) == -1)
503         {
504             ERROR(str, errno);
505         }
506     } while ((str = next_field(str)) != NULL);
507
508     /* return appropriate error string */
509     return(err_string());
510 }
511