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