]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/top/commands.c
top(1): clean up some "const" related 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 static char no_proc_specified[] = " no processes specified";
368 static char invalid_signal_number[] = " invalid_signal_number";
369 static char bad_signal_name[] = " bad signal name";
370 static char bad_pri_value[] = " bad priority value";
371
372 /*
373  *  kill_procs(str) - send signals to processes, much like the "kill"
374  *              command does; invoked in response to 'k'.
375  */
376
377 char *
378 kill_procs(char *str)
379 {
380     char *nptr;
381     int signum = SIGTERM;       /* default */
382     int procnum;
383     struct sigdesc *sigp;
384     int uid;
385
386     /* reset error array */
387     ERR_RESET;
388
389     /* remember our uid */
390     uid = getuid();
391
392     /* skip over leading white space */
393     while (isspace(*str)) str++;
394
395     if (str[0] == '-')
396     {
397         /* explicit signal specified */
398         if ((nptr = next_field(str)) == NULL)
399         {
400             return(no_proc_specified);
401         }
402
403         if (isdigit(str[1]))
404         {
405             scanint(str + 1, &signum);
406             if (signum <= 0 || signum >= NSIG)
407             {
408                 return(invalid_signal_number);
409             }
410         }
411         else 
412         {
413             /* translate the name into a number */
414             for (sigp = sigdesc; sigp->name != NULL; sigp++)
415             {
416                 if (strcmp(sigp->name, str + 1) == 0)
417                 {
418                     signum = sigp->number;
419                     break;
420                 }
421             }
422
423             /* was it ever found */
424             if (sigp->name == NULL)
425             {
426                 return(bad_signal_name);
427             }
428         }
429         /* put the new pointer in place */
430         str = nptr;
431     }
432
433     /* loop thru the string, killing processes */
434     do
435     {
436         if (scanint(str, &procnum) == -1)
437         {
438             ERROR(str, 0);
439         }
440         else
441         {
442             /* check process owner if we're not root */
443             if (uid && (uid != proc_owner(procnum)))
444             {
445                 ERROR(str, EACCES);
446             }
447             /* go in for the kill */
448             else if (kill(procnum, signum) == -1)
449             {
450                 /* chalk up an error */
451                 ERROR(str, errno);
452             }
453         }
454     } while ((str = next_field(str)) != NULL);
455
456     /* return appropriate error string */
457     return(err_string());
458 }
459
460 /*
461  *  renice_procs(str) - change the "nice" of processes, much like the
462  *              "renice" command does; invoked in response to 'r'.
463  */
464
465 char *
466 renice_procs(char *str)
467 {
468     char negate;
469     int prio;
470     int procnum;
471     int uid;
472
473     ERR_RESET;
474     uid = getuid();
475
476     /* allow for negative priority values */
477     if ((negate = (*str == '-')) != 0)
478     {
479         /* move past the minus sign */
480         str++;
481     }
482
483     /* use procnum as a temporary holding place and get the number */
484     procnum = scanint(str, &prio);
485
486     /* negate if necessary */
487     if (negate)
488     {
489         prio = -prio;
490     }
491
492     /* check for validity */
493     if (procnum == -1 || prio < PRIO_MIN || prio > PRIO_MAX)
494     {
495         return(bad_pri_value);
496     }
497
498     /* move to the first process number */
499     if ((str = next_field(str)) == NULL)
500     {
501         return(no_proc_specified);
502     }
503
504     /* loop thru the process numbers, renicing each one */
505     do
506     {
507         if (scanint(str, &procnum) == -1)
508         {
509             ERROR(str, 0);
510         }
511
512         /* check process owner if we're not root */
513         else if (uid && (uid != proc_owner(procnum)))
514         {
515             ERROR(str, EACCES);
516         }
517         else if (setpriority(PRIO_PROCESS, procnum, prio) == -1)
518         {
519             ERROR(str, errno);
520         }
521     } while ((str = next_field(str)) != NULL);
522
523     /* return appropriate error string */
524     return(err_string());
525 }
526