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