]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/top/top.c
Merge branch 'releng/11.3' into releng-CDN/11.3
[FreeBSD/FreeBSD.git] / contrib / top / top.c
1 char *copyright =
2     "Copyright (c) 1984 through 1996, William LeFebvre";
3
4 /*
5  *  Top users/processes display for Unix
6  *  Version 3
7  *
8  *  This program may be freely redistributed,
9  *  but this entire comment MUST remain intact.
10  *
11  *  Copyright (c) 1984, 1989, William LeFebvre, Rice University
12  *  Copyright (c) 1989 - 1994, William LeFebvre, Northwestern University
13  *  Copyright (c) 1994, 1995, William LeFebvre, Argonne National Laboratory
14  *  Copyright (c) 1996, William LeFebvre, Group sys Consulting
15  *
16  * $FreeBSD$
17  */
18
19 /*
20  *  See the file "Changes" for information on version-to-version changes.
21  */
22
23 /*
24  *  This file contains "main" and other high-level routines.
25  */
26
27 /*
28  * The following preprocessor variables, when defined, are used to
29  * distinguish between different Unix implementations:
30  *
31  *      SIGHOLD  - use SVR4 sighold function when defined
32  *      SIGRELSE - use SVR4 sigrelse function when defined
33  *      FD_SET   - macros FD_SET and FD_ZERO are used when defined
34  */
35
36 #include "os.h"
37
38 #include <sys/jail.h>
39 #include <sys/time.h>
40
41 #include <ctype.h>
42 #include <curses.h>
43 #include <errno.h>
44 #include <jail.h>
45 #include <setjmp.h>
46 #include <signal.h>
47 #include <unistd.h>
48
49 /* includes specific to top */
50 #include "commands.h"
51 #include "display.h"            /* interface to display package */
52 #include "screen.h"             /* interface to screen package */
53 #include "top.h"
54 #include "top.local.h"
55 #include "boolean.h"
56 #include "machine.h"
57 #include "utils.h"
58 #include "username.h"
59
60 /* Size of the stdio buffer given to stdout */
61 #define Buffersize      2048
62
63 /* The buffer that stdio will use */
64 char stdoutbuf[Buffersize];
65
66 /* build Signal masks */
67 #define Smask(s)        (1 << ((s) - 1))
68
69 /* for getopt: */
70 extern int  optind;
71 extern char *optarg;
72
73 /* imported from screen.c */
74 extern int overstrike;
75
76 static int fmt_flags = 0;
77 int pcpu_stats = No;
78
79 /* signal handling routines */
80 sigret_t leave();
81 sigret_t tstop();
82 #ifdef SIGWINCH
83 sigret_t top_winch(int);
84 #endif
85
86 volatile sig_atomic_t leaveflag;
87 volatile sig_atomic_t tstopflag;
88 volatile sig_atomic_t winchflag;
89
90 /* internal routines */
91 void quit();
92
93 /* values which need to be accessed by signal handlers */
94 static int max_topn;            /* maximum displayable processes */
95
96 /* miscellaneous things */
97 struct process_select ps;
98 char *myname = "top";
99 jmp_buf jmp_int;
100
101 /* routines that don't return int */
102
103 char *username();
104 char *ctime();
105 char *kill_procs();
106 char *renice_procs();
107
108 #ifdef ORDER
109 extern int (*compares[])();
110 #else
111 extern int proc_compare();
112 extern int io_compare();
113 #endif
114 time_t time();
115
116 caddr_t get_process_info();
117
118 /* different routines for displaying the user's identification */
119 /* (values assigned to get_userid) */
120 char *username();
121 char *itoa7();
122
123 /* pointers to display routines */
124 void (*d_loadave)() = i_loadave;
125 void (*d_procstates)() = i_procstates;
126 void (*d_cpustates)() = i_cpustates;
127 void (*d_memory)() = i_memory;
128 void (*d_arc)() = i_arc;
129 void (*d_carc)() = i_carc;
130 void (*d_swap)() = i_swap;
131 void (*d_message)() = i_message;
132 void (*d_header)() = i_header;
133 void (*d_process)() = i_process;
134
135 void reset_display(void);
136
137 static void
138 reset_uids()
139 {
140     for (size_t i = 0; i < TOP_MAX_UIDS; ++i)
141         ps.uid[i] = -1;
142 }
143
144 static int
145 add_uid(int uid)
146 {
147     size_t i = 0;
148
149     /* Add the uid if there's room */
150     for (; i < TOP_MAX_UIDS; ++i)
151     {
152         if (ps.uid[i] == -1 || ps.uid[i] == uid)
153         {
154             ps.uid[i] = uid;
155             break;
156         }
157     }
158
159     return (i == TOP_MAX_UIDS);
160 }
161
162 static void
163 rem_uid(int uid)
164 {
165     size_t i = 0;
166     size_t where = TOP_MAX_UIDS;
167
168     /* Look for the user to remove - no problem if it's not there */
169     for (; i < TOP_MAX_UIDS; ++i)
170     {
171         if (ps.uid[i] == -1)
172             break;
173         if (ps.uid[i] == uid)
174             where = i;
175     }
176
177     /* Make sure we don't leave a hole in the middle */
178     if (where != TOP_MAX_UIDS)
179     {
180         ps.uid[where] = ps.uid[i-1];
181         ps.uid[i-1] = -1;
182     }
183 }
184
185 static int
186 handle_user(char *buf, size_t buflen)
187 {
188     int rc = 0;
189     int uid = -1;
190     char *buf2 = buf;
191
192     new_message(MT_standout, "Username to show (+ for all): ");
193     if (readline(buf, buflen, No) <= 0)
194     {
195         clear_message();
196         return rc;
197     }
198
199     if (buf[0] == '+' || buf[0] == '-')
200     {
201         if (buf[1] == '\0')
202         {
203             reset_uids();
204             goto end;
205         }
206         else
207             ++buf2;
208     }
209
210     if ((uid = userid(buf2)) == -1)
211     {
212         new_message(MT_standout, " %s: unknown user", buf2);
213         rc = 1;
214         goto end;
215     }
216
217     if (buf2 == buf)
218     {
219         reset_uids();
220         ps.uid[0] = uid;
221         goto end;
222     }
223
224     if (buf[0] == '+')
225     {
226         if (add_uid(uid))
227         {
228             new_message(MT_standout, " too many users, reset with '+'");
229             rc = 1;
230             goto end;
231         }
232     }
233     else
234         rem_uid(uid);
235
236 end:
237     putchar('\r');
238     return rc;
239 }
240
241 int
242 main(argc, argv)
243
244 int  argc;
245 char *argv[];
246
247 {
248     register int i;
249     register int active_procs;
250     register int change;
251
252     struct system_info system_info;
253     struct statics statics;
254     caddr_t processes;
255
256     static char tempbuf1[50];
257     static char tempbuf2[50];
258     int old_sigmask;            /* only used for BSD-style signals */
259     int topn = Default_TOPN;
260     int delay = Default_DELAY;
261     int displays = 0;           /* indicates unspecified */
262     int sel_ret = 0;
263     time_t curr_time;
264     char *(*get_userid)() = username;
265     char *uname_field = "USERNAME";
266     char *header_text;
267     char *env_top;
268     char **preset_argv;
269     int  preset_argc = 0;
270     char **av;
271     int  ac;
272     char dostates = No;
273     char do_unames = Yes;
274     char interactive = Maybe;
275     char warnings = 0;
276 #if Default_TOPN == Infinity
277     char topn_specified = No;
278 #endif
279     char ch;
280     char *iptr;
281     char no_command = 1;
282     struct timeval timeout;
283 #ifdef ORDER
284     char *order_name = NULL;
285     int order_index = 0;
286 #endif
287 #ifndef FD_SET
288     /* FD_SET and friends are not present:  fake it */
289     typedef int fd_set;
290 #define FD_ZERO(x)     (*(x) = 0)
291 #define FD_SET(f, x)   (*(x) = 1<<f)
292 #endif
293     fd_set readfds;
294
295 #ifdef ORDER
296     static char command_chars[] = "\f qh?en#sdkriIutHmSCajzPJwo";
297 #else
298     static char command_chars[] = "\f qh?en#sdkriIutHmSCajzPJw";
299 #endif
300 /* these defines enumerate the "strchr"s of the commands in command_chars */
301 #define CMD_redraw      0
302 #define CMD_update      1
303 #define CMD_quit        2
304 #define CMD_help1       3
305 #define CMD_help2       4
306 #define CMD_OSLIMIT     4    /* terminals with OS can only handle commands */
307 #define CMD_errors      5    /* less than or equal to CMD_OSLIMIT          */
308 #define CMD_number1     6
309 #define CMD_number2     7
310 #define CMD_delay       8
311 #define CMD_displays    9
312 #define CMD_kill        10
313 #define CMD_renice      11
314 #define CMD_idletog     12
315 #define CMD_idletog2    13
316 #define CMD_user        14
317 #define CMD_selftog     15
318 #define CMD_thrtog      16
319 #define CMD_viewtog     17
320 #define CMD_viewsys     18
321 #define CMD_wcputog     19
322 #define CMD_showargs    20
323 #define CMD_jidtog      21
324 #define CMD_kidletog    22
325 #define CMD_pcputog     23
326 #define CMD_jail        24
327 #define CMD_swaptog     25
328 #ifdef ORDER
329 #define CMD_order       26
330 #endif
331
332     /* set the buffer for stdout */
333 #ifdef DEBUG
334     extern FILE *debug;
335     debug = fopen("debug.run", "w");
336     setbuffer(stdout, NULL, 0);
337 #else
338     setbuffer(stdout, stdoutbuf, Buffersize);
339 #endif
340
341     /* get our name */
342     if (argc > 0)
343     {
344         if ((myname = strrchr(argv[0], '/')) == 0)
345         {
346             myname = argv[0];
347         }
348         else
349         {
350             myname++;
351         }
352     }
353
354     /* initialize some selection options */
355     ps.idle    = Yes;
356     ps.self    = -1;
357     ps.system  = No;
358     reset_uids();
359     ps.thread  = No;
360     ps.wcpu    = 1;
361     ps.jid     = -1;
362     ps.jail    = No;
363     ps.swap    = No;
364     ps.kidle   = Yes;
365     ps.command = NULL;
366
367     /* get preset options from the environment */
368     if ((env_top = getenv("TOP")) != NULL)
369     {
370         av = preset_argv = argparse(env_top, &preset_argc);
371         ac = preset_argc;
372
373         /* set the dummy argument to an explanatory message, in case
374            getopt encounters a bad argument */
375         preset_argv[0] = "while processing environment";
376     }
377
378     /* process options */
379     do {
380         /* if we're done doing the presets, then process the real arguments */
381         if (preset_argc == 0)
382         {
383             ac = argc;
384             av = argv;
385
386             /* this should keep getopt happy... */
387             optind = 1;
388         }
389
390         while ((i = getopt(ac, av, "CSIHPabijJ:nquvzs:d:U:m:o:tw")) != EOF)
391         {
392             switch(i)
393             {
394               case 'v':                 /* show version number */
395                 fprintf(stderr, "%s: version %s\n",
396                         myname, version_string());
397                 exit(1);
398                 break;
399
400               case 'u':                 /* toggle uid/username display */
401                 do_unames = !do_unames;
402                 break;
403
404               case 'U':                 /* display only username's processes */
405                 if ((ps.uid[0] = userid(optarg)) == -1)
406                 {
407                     fprintf(stderr, "%s: unknown user\n", optarg);
408                     exit(1);
409                 }
410                 break;
411
412               case 'S':                 /* show system processes */
413                 ps.system = !ps.system;
414                 break;
415
416               case 'I':                   /* show idle processes */
417                 ps.idle = !ps.idle;
418                 break;
419
420               case 'i':                 /* go interactive regardless */
421                 interactive = Yes;
422                 break;
423
424               case 'n':                 /* batch, or non-interactive */
425               case 'b':
426                 interactive = No;
427                 break;
428
429               case 'a':
430                 fmt_flags ^= FMT_SHOWARGS;
431                 break;
432
433               case 'd':                 /* number of displays to show */
434                 if ((i = atoiwi(optarg)) == Invalid || i == 0)
435                 {
436                     fprintf(stderr,
437                         "%s: warning: display count should be positive -- option ignored\n",
438                         myname);
439                     warnings++;
440                 }
441                 else
442                 {
443                     displays = i;
444                 }
445                 break;
446
447               case 's':
448                 if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0))
449                 {
450                     fprintf(stderr,
451                         "%s: warning: seconds delay should be positive -- using default\n",
452                         myname);
453                     delay = Default_DELAY;
454                     warnings++;
455                 }
456                 break;
457
458               case 'q':         /* be quick about it */
459                 /* only allow this if user is really root */
460                 if (getuid() == 0)
461                 {
462                     /* be very un-nice! */
463                     (void) nice(-20);
464                 }
465                 else
466                 {
467                     fprintf(stderr,
468                         "%s: warning: `-q' option can only be used by root\n",
469                         myname);
470                     warnings++;
471                 }
472                 break;
473
474               case 'm':         /* select display mode */
475                 if (strcmp(optarg, "io") == 0) {
476                         displaymode = DISP_IO;
477                 } else if (strcmp(optarg, "cpu") == 0) {
478                         displaymode = DISP_CPU;
479                 } else {
480                         fprintf(stderr,
481                         "%s: warning: `-m' option can only take args "
482                         "'io' or 'cpu'\n",
483                         myname);
484                         exit(1);
485                 }
486                 break;
487
488               case 'o':         /* select sort order */
489 #ifdef ORDER
490                 order_name = optarg;
491 #else
492                 fprintf(stderr,
493                         "%s: this platform does not support arbitrary ordering.  Sorry.\n",
494                         myname);
495                 warnings++;
496 #endif
497                 break;
498
499               case 't':
500                 ps.self = (ps.self == -1) ? getpid() : -1;
501                 break;
502
503               case 'C':
504                 ps.wcpu = !ps.wcpu;
505                 break;
506
507               case 'H':
508                 ps.thread = !ps.thread;
509                 break;
510
511               case 'j':
512                 ps.jail = !ps.jail;
513                 break;
514
515               case 'J':                 /* display only jail's processes */
516                 if ((ps.jid = jail_getid(optarg)) == -1)
517                 {
518                     fprintf(stderr, "%s: unknown jail\n", optarg);
519                     exit(1);
520                 }
521                 ps.jail = 1;
522                 break;
523
524               case 'P':
525                 pcpu_stats = !pcpu_stats;
526                 break;
527
528               case 'w':
529                 ps.swap = 1;
530                 break;
531
532               case 'z':
533                 ps.kidle = !ps.kidle;
534                 break;
535
536               default:
537                 fprintf(stderr,
538 "Top version %s\n"
539 "Usage: %s [-abCHIijnPqStuvwz] [-d count] [-m io | cpu] [-o field] [-s time]\n"
540 "       [-J jail] [-U username] [number]\n",
541                         version_string(), myname);
542                 exit(1);
543             }
544         }
545
546         /* get count of top processes to display (if any) */
547         if (optind < ac)
548         {
549             if ((topn = atoiwi(av[optind])) == Invalid)
550             {
551                 fprintf(stderr,
552                         "%s: warning: process display count should be non-negative -- using default\n",
553                         myname);
554                 warnings++;
555             }
556 #if Default_TOPN == Infinity
557             else
558             {
559                 topn_specified = Yes;
560             }
561 #endif
562         }
563
564         /* tricky:  remember old value of preset_argc & set preset_argc = 0 */
565         i = preset_argc;
566         preset_argc = 0;
567
568     /* repeat only if we really did the preset arguments */
569     } while (i != 0);
570
571     /* set constants for username/uid display correctly */
572     if (!do_unames)
573     {
574         uname_field = "   UID  ";
575         get_userid = itoa7;
576     }
577
578     /* initialize the kernel memory interface */
579     if (machine_init(&statics, do_unames) == -1)
580     {
581         exit(1);
582     }
583
584 #ifdef ORDER
585     /* determine sorting order index, if necessary */
586     if (order_name != NULL)
587     {
588         if ((order_index = string_index(order_name, statics.order_names)) == -1)
589         {
590             char **pp;
591
592             fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n",
593                     myname, order_name);
594             fprintf(stderr, "\tTry one of these:");
595             pp = statics.order_names;
596             while (*pp != NULL)
597             {
598                 fprintf(stderr, " %s", *pp++);
599             }
600             fputc('\n', stderr);
601             exit(1);
602         }
603     }
604 #endif
605
606 #ifdef no_initialization_needed
607     /* initialize the hashing stuff */
608     if (do_unames)
609     {
610         init_hash();
611     }
612 #endif
613
614     /* initialize termcap */
615     init_termcap(interactive);
616
617     /* get the string to use for the process area header */
618     header_text = format_header(uname_field);
619
620     /* initialize display interface */
621     if ((max_topn = display_init(&statics)) == -1)
622     {
623         fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
624         exit(4);
625     }
626     
627     /* print warning if user requested more processes than we can display */
628     if (topn > max_topn)
629     {
630         fprintf(stderr,
631                 "%s: warning: this terminal can only display %d processes.\n",
632                 myname, max_topn);
633         warnings++;
634     }
635
636     /* adjust for topn == Infinity */
637     if (topn == Infinity)
638     {
639         /*
640          *  For smart terminals, infinity really means everything that can
641          *  be displayed, or Largest.
642          *  On dumb terminals, infinity means every process in the system!
643          *  We only really want to do that if it was explicitly specified.
644          *  This is always the case when "Default_TOPN != Infinity".  But if
645          *  topn wasn't explicitly specified and we are on a dumb terminal
646          *  and the default is Infinity, then (and only then) we use
647          *  "Nominal_TOPN" instead.
648          */
649 #if Default_TOPN == Infinity
650         topn = smart_terminal ? Largest :
651                     (topn_specified ? Largest : Nominal_TOPN);
652 #else
653         topn = Largest;
654 #endif
655     }
656
657     /* set header display accordingly */
658     display_header(topn > 0);
659
660     /* determine interactive state */
661     if (interactive == Maybe)
662     {
663         interactive = smart_terminal;
664     }
665
666     /* if # of displays not specified, fill it in */
667     if (displays == 0)
668     {
669         displays = smart_terminal ? Infinity : 1;
670     }
671
672     /* hold interrupt signals while setting up the screen and the handlers */
673 #ifdef SIGHOLD
674     sighold(SIGINT);
675     sighold(SIGQUIT);
676     sighold(SIGTSTP);
677 #else
678     old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP));
679 #endif
680     init_screen();
681     (void) signal(SIGINT, leave);
682     (void) signal(SIGQUIT, leave);
683     (void) signal(SIGTSTP, tstop);
684 #ifdef SIGWINCH
685     (void) signal(SIGWINCH, top_winch);
686 #endif
687 #ifdef SIGRELSE
688     sigrelse(SIGINT);
689     sigrelse(SIGQUIT);
690     sigrelse(SIGTSTP);
691 #else
692     (void) sigsetmask(old_sigmask);
693 #endif
694     if (warnings)
695     {
696         fputs("....", stderr);
697         fflush(stderr);                 /* why must I do this? */
698         sleep((unsigned)(3 * warnings));
699         fputc('\n', stderr);
700     }
701
702 restart:
703
704     /*
705      *  main loop -- repeat while display count is positive or while it
706      *          indicates infinity (by being -1)
707      */
708
709     while ((displays == -1) || (displays-- > 0))
710     {
711         int (*compare)();
712
713             
714         /* get the current stats */
715         get_system_info(&system_info);
716
717 #ifdef ORDER
718         compare = compares[order_index];
719 #else
720         if (displaymode == DISP_CPU)
721                 compare = proc_compare;
722         else
723                 compare = io_compare;
724 #endif
725
726         /* get the current set of processes */
727         processes =
728                 get_process_info(&system_info, &ps, compare);
729
730         /* display the load averages */
731         (*d_loadave)(system_info.last_pid,
732                      system_info.load_avg);
733
734         /* display the current time */
735         /* this method of getting the time SHOULD be fairly portable */
736         time(&curr_time);
737         i_uptime(&system_info.boottime, &curr_time);
738         i_timeofday(&curr_time);
739
740         /* display process state breakdown */
741         (*d_procstates)(system_info.p_total,
742                         system_info.procstates);
743
744         /* display the cpu state percentage breakdown */
745         if (dostates)   /* but not the first time */
746         {
747             (*d_cpustates)(system_info.cpustates);
748         }
749         else
750         {
751             /* we'll do it next time */
752             if (smart_terminal)
753             {
754                 z_cpustates();
755             }
756             else
757             {
758                 putchar('\n');
759             }
760             dostates = Yes;
761         }
762
763         /* display memory stats */
764         (*d_memory)(system_info.memory);
765         (*d_arc)(system_info.arc);
766         (*d_carc)(system_info.carc);
767
768         /* display swap stats */
769         (*d_swap)(system_info.swap);
770
771         /* handle message area */
772         (*d_message)();
773
774         /* update the header area */
775         (*d_header)(header_text);
776     
777         if (topn > 0)
778         {
779             /* determine number of processes to actually display */
780             /* this number will be the smallest of:  active processes,
781                number user requested, number current screen accomodates */
782             active_procs = system_info.P_ACTIVE;
783             if (active_procs > topn)
784             {
785                 active_procs = topn;
786             }
787             if (active_procs > max_topn)
788             {
789                 active_procs = max_topn;
790             }
791
792             /* now show the top "n" processes. */
793             for (i = 0; i < active_procs; i++)
794             {
795                 (*d_process)(i, format_next_process(processes, get_userid,
796                              fmt_flags));
797             }
798         }
799         else
800         {
801             i = 0;
802         }
803
804         /* do end-screen processing */
805         u_endscreen(i);
806
807         /* now, flush the output buffer */
808         if (fflush(stdout) != 0)
809         {
810             new_message(MT_standout, " Write error on stdout");
811             putchar('\r');
812             quit(1);
813             /*NOTREACHED*/
814         }
815
816         /* only do the rest if we have more displays to show */
817         if (displays)
818         {
819             /* switch out for new display on smart terminals */
820             if (smart_terminal)
821             {
822                 if (overstrike)
823                 {
824                     reset_display();
825                 }
826                 else
827                 {
828                     d_loadave = u_loadave;
829                     d_procstates = u_procstates;
830                     d_cpustates = u_cpustates;
831                     d_memory = u_memory;
832                     d_arc = u_arc;
833                     d_carc = u_carc;
834                     d_swap = u_swap;
835                     d_message = u_message;
836                     d_header = u_header;
837                     d_process = u_process;
838                 }
839             }
840     
841             no_command = Yes;
842             if (!interactive)
843             {
844                 sleep(delay);
845                 if (leaveflag) {
846                     end_screen();
847                     exit(0);
848                 }
849             }
850             else while (no_command)
851             {
852                 /* assume valid command unless told otherwise */
853                 no_command = No;
854
855                 /* set up arguments for select with timeout */
856                 FD_ZERO(&readfds);
857                 FD_SET(0, &readfds);            /* for standard input */
858                 timeout.tv_sec  = delay;
859                 timeout.tv_usec = 0;
860
861                 if (leaveflag) {
862                     end_screen();
863                     exit(0);
864                 }
865
866                 if (tstopflag) {
867                     /* move to the lower left */
868                     end_screen();
869                     fflush(stdout);
870
871                     /* default the signal handler action */
872                     (void) signal(SIGTSTP, SIG_DFL);
873
874                     /* unblock the signal and send ourselves one */
875 #ifdef SIGRELSE
876                     sigrelse(SIGTSTP);
877 #else
878                     (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1)));
879 #endif
880                     (void) kill(0, SIGTSTP);
881
882                     /* reset the signal handler */
883                     (void) signal(SIGTSTP, tstop);
884
885                     /* reinit screen */
886                     reinit_screen();
887                     reset_display();
888                     tstopflag = 0;
889                     goto restart;
890                 }
891
892                 if (winchflag) {
893                     /* reascertain the screen dimensions */
894                     get_screensize();
895
896                     /* tell display to resize */
897                     max_topn = display_resize();
898
899                     /* reset the signal handler */
900                     (void) signal(SIGWINCH, top_winch);
901
902                     reset_display();
903                     winchflag = 0;
904                     goto restart;
905                 }
906
907                 /* wait for either input or the end of the delay period */
908                 sel_ret = select(2, &readfds, NULL, NULL, &timeout);
909                 if (sel_ret < 0 && errno != EINTR)
910                     quit(0);
911                 if (sel_ret > 0)
912                 {
913                     int newval;
914                     char *errmsg;
915     
916                     /* something to read -- clear the message area first */
917                     clear_message();
918
919                     /* now read it and convert to command strchr */
920                     /* (use "change" as a temporary to hold strchr) */
921                     if (read(0, &ch, 1) != 1)
922                     {
923                         /* read error: either 0 or -1 */
924                         new_message(MT_standout, " Read error on stdin");
925                         putchar('\r');
926                         quit(1);
927                         /*NOTREACHED*/
928                     }
929                     if ((iptr = strchr(command_chars, ch)) == NULL)
930                     {
931                         if (ch != '\r' && ch != '\n')
932                         {
933                             /* illegal command */
934                             new_message(MT_standout, " Command not understood");
935                         }
936                         putchar('\r');
937                         no_command = Yes;
938                     }
939                     else
940                     {
941                         change = iptr - command_chars;
942                         if (overstrike && change > CMD_OSLIMIT)
943                         {
944                             /* error */
945                             new_message(MT_standout,
946                             " Command cannot be handled by this terminal");
947                             putchar('\r');
948                             no_command = Yes;
949                         }
950                         else switch(change)
951                         {
952                             case CMD_redraw:    /* redraw screen */
953                                 reset_display();
954                                 break;
955     
956                             case CMD_update:    /* merely update display */
957                                 /* is the load average high? */
958                                 if (system_info.load_avg[0] > LoadMax)
959                                 {
960                                     /* yes, go home for visual feedback */
961                                     go_home();
962                                     fflush(stdout);
963                                 }
964                                 break;
965             
966                             case CMD_quit:      /* quit */
967                                 quit(0);
968                                 /*NOTREACHED*/
969                                 break;
970             
971                             case CMD_help1:     /* help */
972                             case CMD_help2:
973                                 reset_display();
974                                 top_clear();
975                                 show_help();
976                                 top_standout("Hit any key to continue: ");
977                                 fflush(stdout);
978                                 (void) read(0, &ch, 1);
979                                 break;
980         
981                             case CMD_errors:    /* show errors */
982                                 if (error_count() == 0)
983                                 {
984                                     new_message(MT_standout,
985                                         " Currently no errors to report.");
986                                     putchar('\r');
987                                     no_command = Yes;
988                                 }
989                                 else
990                                 {
991                                     reset_display();
992                                     top_clear();
993                                     show_errors();
994                                     top_standout("Hit any key to continue: ");
995                                     fflush(stdout);
996                                     (void) read(0, &ch, 1);
997                                 }
998                                 break;
999         
1000                             case CMD_number1:   /* new number */
1001                             case CMD_number2:
1002                                 new_message(MT_standout,
1003                                     "Number of processes to show: ");
1004                                 newval = readline(tempbuf1, 8, Yes);
1005                                 if (newval > -1)
1006                                 {
1007                                     if (newval > max_topn)
1008                                     {
1009                                         new_message(MT_standout | MT_delayed,
1010                                           " This terminal can only display %d processes.",
1011                                           max_topn);
1012                                         putchar('\r');
1013                                     }
1014
1015                                     if (newval == 0)
1016                                     {
1017                                         /* inhibit the header */
1018                                         display_header(No);
1019                                     }
1020                                     else if (newval > topn && topn == 0)
1021                                     {
1022                                         /* redraw the header */
1023                                         display_header(Yes);
1024                                         d_header = i_header;
1025                                     }
1026                                     topn = newval;
1027                                 }
1028                                 break;
1029             
1030                             case CMD_delay:     /* new seconds delay */
1031                                 new_message(MT_standout, "Seconds to delay: ");
1032                                 if ((i = readline(tempbuf1, 8, Yes)) > -1)
1033                                 {
1034                                     if ((delay = i) == 0 && getuid() != 0)
1035                                     {
1036                                         delay = 1;
1037                                     }
1038                                 }
1039                                 clear_message();
1040                                 break;
1041         
1042                             case CMD_displays:  /* change display count */
1043                                 new_message(MT_standout,
1044                                         "Displays to show (currently %s): ",
1045                                         displays == -1 ? "infinite" :
1046                                                          itoa(displays));
1047                                 if ((i = readline(tempbuf1, 10, Yes)) > 0)
1048                                 {
1049                                     displays = i;
1050                                 }
1051                                 else if (i == 0)
1052                                 {
1053                                     quit(0);
1054                                 }
1055                                 clear_message();
1056                                 break;
1057     
1058                             case CMD_kill:      /* kill program */
1059                                 new_message(0, "kill ");
1060                                 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1061                                 {
1062                                     if ((errmsg = kill_procs(tempbuf2)) != NULL)
1063                                     {
1064                                         new_message(MT_standout, "%s", errmsg);
1065                                         putchar('\r');
1066                                         no_command = Yes;
1067                                     }
1068                                 }
1069                                 else
1070                                 {
1071                                     clear_message();
1072                                 }
1073                                 break;
1074             
1075                             case CMD_renice:    /* renice program */
1076                                 new_message(0, "renice ");
1077                                 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1078                                 {
1079                                     if ((errmsg = renice_procs(tempbuf2)) != NULL)
1080                                     {
1081                                         new_message(MT_standout, "%s", errmsg);
1082                                         putchar('\r');
1083                                         no_command = Yes;
1084                                     }
1085                                 }
1086                                 else
1087                                 {
1088                                     clear_message();
1089                                 }
1090                                 break;
1091
1092                             case CMD_idletog:
1093                             case CMD_idletog2:
1094                                 ps.idle = !ps.idle;
1095                                 new_message(MT_standout | MT_delayed,
1096                                     " %sisplaying idle processes.",
1097                                     ps.idle ? "D" : "Not d");
1098                                 putchar('\r');
1099                                 break;
1100
1101                             case CMD_selftog:
1102                                 ps.self = (ps.self == -1) ? getpid() : -1;
1103                                 new_message(MT_standout | MT_delayed,
1104                                     " %sisplaying self.",
1105                                     (ps.self == -1) ? "D" : "Not d");
1106                                 putchar('\r');
1107                                 break;
1108
1109                             case CMD_user:
1110                                 if (handle_user(tempbuf2, sizeof(tempbuf2)))
1111                                     no_command = Yes;
1112                                 break;
1113             
1114                             case CMD_thrtog:
1115                                 ps.thread = !ps.thread;
1116                                 new_message(MT_standout | MT_delayed,
1117                                     " Displaying threads %s",
1118                                     ps.thread ? "separately" : "as a count");
1119                                 header_text = format_header(uname_field);
1120                                 reset_display();
1121                                 putchar('\r');
1122                                 break;
1123                             case CMD_wcputog:
1124                                 ps.wcpu = !ps.wcpu;
1125                                 new_message(MT_standout | MT_delayed,
1126                                     " Displaying %s CPU",
1127                                     ps.wcpu ? "weighted" : "raw");
1128                                 header_text = format_header(uname_field);
1129                                 reset_display();
1130                                 putchar('\r');
1131                                 break;
1132                             case CMD_viewtog:
1133                                 if (++displaymode == DISP_MAX)
1134                                         displaymode = 0;
1135                                 header_text = format_header(uname_field);
1136                                 display_header(Yes);
1137                                 d_header = i_header;
1138                                 reset_display();
1139                                 break;
1140                             case CMD_viewsys:
1141                                 ps.system = !ps.system;
1142                                 break;
1143                             case CMD_showargs:
1144                                 fmt_flags ^= FMT_SHOWARGS;
1145                                 break;
1146 #ifdef ORDER
1147                             case CMD_order:
1148                                 new_message(MT_standout,
1149                                     "Order to sort: ");
1150                                 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1151                                 {
1152                                   if ((i = string_index(tempbuf2, statics.order_names)) == -1)
1153                                         {
1154                                           new_message(MT_standout,
1155                                               " %s: unrecognized sorting order", tempbuf2);
1156                                           no_command = Yes;
1157                                     }
1158                                     else
1159                                     {
1160                                         order_index = i;
1161                                     }
1162                                     putchar('\r');
1163                                 }
1164                                 else
1165                                 {
1166                                     clear_message();
1167                                 }
1168                                 break;
1169 #endif
1170                             case CMD_jidtog:
1171                                 ps.jail = !ps.jail;
1172                                 new_message(MT_standout | MT_delayed,
1173                                     " %sisplaying jail ID.",
1174                                     ps.jail ? "D" : "Not d");
1175                                 header_text = format_header(uname_field);
1176                                 reset_display();
1177                                 putchar('\r');
1178                                 break;
1179
1180                             case CMD_jail:
1181                                 new_message(MT_standout,
1182                                     "Jail to show (+ for all): ");
1183                                 if (readline(tempbuf2, sizeof(tempbuf2), No) > 0)
1184                                 {
1185                                     if (tempbuf2[0] == '+' &&
1186                                         tempbuf2[1] == '\0')
1187                                     {
1188                                         ps.jid = -1;
1189                                     }
1190                                     else if ((i = jail_getid(tempbuf2)) == -1)
1191                                     {
1192                                         new_message(MT_standout,
1193                                             " %s: unknown jail", tempbuf2);
1194                                         no_command = Yes;
1195                                     }
1196                                     else
1197                                     {
1198                                         ps.jid = i;
1199                                     }
1200                                     if (ps.jail == 0) {
1201                                             ps.jail = 1;
1202                                             new_message(MT_standout |
1203                                                 MT_delayed, " Displaying jail "
1204                                                 "ID.");
1205                                             header_text =
1206                                                 format_header(uname_field);
1207                                             reset_display();
1208                                     }
1209                                     putchar('\r');
1210                                 }
1211                                 else
1212                                 {
1213                                     clear_message();
1214                                 }
1215                                 break;
1216             
1217                             case CMD_kidletog:
1218                                 ps.kidle = !ps.kidle;
1219                                 new_message(MT_standout | MT_delayed,
1220                                     " %sisplaying system idle process.",
1221                                     ps.kidle ? "D" : "Not d");
1222                                 putchar('\r');
1223                                 break;
1224                             case CMD_pcputog:
1225                                 pcpu_stats = !pcpu_stats;
1226                                 new_message(MT_standout | MT_delayed,
1227                                     " Displaying %sCPU statistics.",
1228                                     pcpu_stats ? "per-" : "global ");
1229                                 toggle_pcpustats();
1230                                 max_topn = display_updatecpus(&statics);
1231                                 reset_display();
1232                                 putchar('\r');
1233                                 break;
1234                             case CMD_swaptog:
1235                                 ps.swap = !ps.swap;
1236                                 new_message(MT_standout | MT_delayed,
1237                                     " %sisplaying per-process swap usage.",
1238                                     ps.swap ? "D" : "Not d");
1239                                 header_text = format_header(uname_field);
1240                                 reset_display();
1241                                 putchar('\r');
1242                                 break;
1243                             default:
1244                                 new_message(MT_standout, " BAD CASE IN SWITCH!");
1245                                 putchar('\r');
1246                         }
1247                     }
1248
1249                     /* flush out stuff that may have been written */
1250                     fflush(stdout);
1251                 }
1252             }
1253         }
1254     }
1255
1256 #ifdef DEBUG
1257     fclose(debug);
1258 #endif
1259     quit(0);
1260     /*NOTREACHED*/
1261 }
1262
1263 /*
1264  *  reset_display() - reset all the display routine pointers so that entire
1265  *      screen will get redrawn.
1266  */
1267
1268 void
1269 reset_display()
1270
1271 {
1272     d_loadave    = i_loadave;
1273     d_procstates = i_procstates;
1274     d_cpustates  = i_cpustates;
1275     d_memory     = i_memory;
1276     d_arc        = i_arc;
1277     d_carc       = i_carc;
1278     d_swap       = i_swap;
1279     d_message    = i_message;
1280     d_header     = i_header;
1281     d_process    = i_process;
1282 }
1283
1284 /*
1285  *  signal handlers
1286  */
1287
1288 sigret_t leave()        /* exit under normal conditions -- INT handler */
1289
1290 {
1291     leaveflag = 1;
1292 }
1293
1294 sigret_t tstop(i)       /* SIGTSTP handler */
1295
1296 int i;
1297
1298 {
1299     tstopflag = 1;
1300 }
1301
1302 #ifdef SIGWINCH
1303 sigret_t top_winch(int i)               /* SIGWINCH handler */
1304 {
1305     winchflag = 1;
1306 }
1307 #endif
1308
1309 void quit(status)               /* exit under duress */
1310
1311 int status;
1312
1313 {
1314     end_screen();
1315     exit(status);
1316     /*NOTREACHED*/
1317 }