2 "Copyright (c) 1984 through 1996, William LeFebvre";
5 * Top users/processes display for Unix
8 * This program may be freely redistributed,
9 * but this entire comment MUST remain intact.
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
16 * $FreeBSD: src/contrib/top/top.c,v 1.4.6.5 2002/08/11 17:09:25 dwmalone Exp $
17 * $DragonFly: src/contrib/top/top.c,v 1.4 2006/10/03 12:20:11 y0netan1 Exp $
21 * See the file "Changes" for information on version-to-version changes.
25 * This file contains "main" and other high-level routines.
29 * The following preprocessor variables, when defined, are used to
30 * distinguish between different Unix implementations:
32 * SIGHOLD - use SVR4 sighold function when defined
33 * SIGRELSE - use SVR4 sigrelse function when defined
34 * FD_SET - macros FD_SET and FD_ZERO are used when defined
44 /* includes specific to top */
45 #include "display.h" /* interface to display package */
46 #include "screen.h" /* interface to screen package */
48 #include "top.local.h"
53 /* Size of the stdio buffer given to stdout */
54 #define Buffersize 2048
56 /* The buffer that stdio will use */
57 char stdoutbuf
[Buffersize
];
59 /* build Signal masks */
60 #define Smask(s) (1 << ((s) - 1))
66 /* imported from screen.c */
67 extern int overstrike
;
69 /* signal handling routines */
77 volatile sig_atomic_t leaveflag
;
78 volatile sig_atomic_t tstopflag
;
79 volatile sig_atomic_t winchflag
;
81 /* internal routines */
84 /* values which need to be accessed by signal handlers */
85 static int max_topn
; /* maximum displayable processes */
87 /* miscellaneous things */
91 /* routines that don't return int */
99 extern int (*proc_compares
[])();
101 extern int proc_compare();
105 caddr_t
get_process_info();
107 /* different routines for displaying the user's identification */
108 /* (values assigned to get_userid) */
112 /* display routines that need to be predeclared */
117 int i_cpustates(struct system_info
*);
118 int u_cpustates(struct system_info
*);
130 /* pointers to display routines */
131 int (*d_loadave
)() = i_loadave
;
132 int (*d_procstates
)() = i_procstates
;
133 int (*d_cpustates
)(struct system_info
*) = i_cpustates
;
134 int (*d_memory
)() = i_memory
;
135 int (*d_swap
)() = i_swap
;
136 int (*d_message
)() = i_message
;
137 int (*d_header
)() = i_header
;
138 int (*d_process
)() = i_process
;
149 register int active_procs
;
152 struct system_info system_info
;
153 struct statics statics
;
156 static char tempbuf1
[50];
157 static char tempbuf2
[50];
158 int old_sigmask
; /* only used for BSD-style signals */
159 int topn
= Default_TOPN
;
160 int delay
= Default_DELAY
;
161 int displays
= 0; /* indicates unspecified */
164 char *(*get_userid
)() = username
;
165 char *uname_field
= "USERNAME";
173 char do_unames
= Yes
;
174 char interactive
= Maybe
;
176 #if Default_TOPN == Infinity
177 char topn_specified
= No
;
182 struct timeval timeout
;
183 struct process_select ps
;
185 char *order_name
= NULL
;
189 /* FD_SET and friends are not present: fake it */
191 #define FD_ZERO(x) (*(x) = 0)
192 #define FD_SET(f, x) (*(x) = 1<<f)
197 static char command_chars
[] = "\f qh?en#sdkriIutTOSo";
199 static char command_chars
[] = "\f qh?en#sdkriIutTOSO";
201 /* these defines enumerate the "strchr"s of the commands in command_chars */
207 #define CMD_OSLIMIT 4 /* terminals with OS can only handle commands */
208 #define CMD_errors 5 /* less than or equal to CMD_OSLIMIT */
209 #define CMD_number1 6
210 #define CMD_number2 7
212 #define CMD_displays 9
214 #define CMD_renice 11
215 #define CMD_idletog 12
216 #define CMD_idletog2 13
218 #define CMD_selftog 15
219 #define CMD_threads 16
220 #define CMD_othreads 17
221 #define CMD_system 18
226 /* set the buffer for stdout */
229 debug
= fopen("debug.run", "w");
230 setbuffer(stdout
, NULL
, 0);
232 setbuffer(stdout
, stdoutbuf
, Buffersize
);
238 if ((myname
= strrchr(argv
[0], '/')) == 0)
248 /* initialize some selection options */
253 ps
.only_threads
= No
;
257 /* get preset options from the environment */
258 if ((env_top
= getenv("TOP")) != NULL
)
260 av
= preset_argv
= argparse(env_top
, &preset_argc
);
263 /* set the dummy argument to an explanatory message, in case
264 getopt encounters a bad argument */
265 preset_argv
[0] = "while processing environment";
268 /* process options */
270 /* if we're done doing the presets, then process the real arguments */
271 if (preset_argc
== 0)
276 /* this should keep getopt happy... */
280 while ((i
= getopt(ac
, av
, "SITONbinquvs:d:U:o:t")) != EOF
)
284 case 'v': /* show version number */
285 fprintf(stderr
, "%s: version %s\n",
286 myname
, version_string());
290 case 'u': /* toggle uid/username display */
291 do_unames
= !do_unames
;
294 case 'U': /* display only username's processes */
295 if ((ps
.uid
= userid(optarg
)) == -1)
297 fprintf(stderr
, "%s: unknown user\n", optarg
);
302 case 'S': /* show system processes */
303 ps
.system
= !ps
.system
;
306 case 'I': /* show idle processes */
311 ps
.only_threads
= !ps
.only_threads
; /* only threads */
315 ps
.threads
= !ps
.threads
; /* show threads */
318 case 'i': /* go interactive regardless */
322 case 'n': /* batch, or non-interactive */
327 case 'd': /* number of displays to show */
328 if ((i
= atoiwi(optarg
)) == Invalid
|| i
== 0)
331 "%s: warning: display count should be positive -- option ignored\n",
342 if ((delay
= atoi(optarg
)) < 0 || (delay
== 0 && getuid() != 0))
345 "%s: warning: seconds delay should be positive -- using default\n",
347 delay
= Default_DELAY
;
352 case 'q': /* be quick about it */
353 /* only allow this if user is really root */
356 /* be very un-nice! */
362 "%s: warning: `-q' option can only be used by root\n",
368 case 'o': /* select sort order */
373 "%s: this platform does not support arbitrary ordering. Sorry.\n",
380 ps
.self
= (ps
.self
== -1) ? getpid() : -1;
386 Usage: %s [-ISbinqut] [-d x] [-s x] [-o field] [-U username] [number]\n",
387 version_string(), myname
);
392 /* get count of top processes to display (if any) */
395 if ((topn
= atoiwi(av
[optind
])) == Invalid
)
398 "%s: warning: process display count should be non-negative -- using default\n",
402 #if Default_TOPN == Infinity
405 topn_specified
= Yes
;
410 /* tricky: remember old value of preset_argc & set preset_argc = 0 */
414 /* repeat only if we really did the preset arguments */
417 /* set constants for username/uid display correctly */
420 uname_field
= " UID ";
424 /* initialize the kernel memory interface */
425 if (machine_init(&statics
) == -1)
431 /* determine sorting order index, if necessary */
432 if (order_name
!= NULL
)
434 if ((order_index
= string_index(order_name
, statics
.order_names
)) == -1)
438 fprintf(stderr
, "%s: '%s' is not a recognized sorting order.\n",
440 fprintf(stderr
, "\tTry one of these:");
441 pp
= statics
.order_names
;
444 fprintf(stderr
, " %s", *pp
++);
452 #ifdef no_initialization_needed
453 /* initialize the hashing stuff */
460 /* initialize termcap */
461 init_termcap(interactive
);
463 /* get the string to use for the process area header */
464 header_text
= format_header(uname_field
);
466 /* initialize display interface */
467 if ((max_topn
= display_init(&statics
)) == -1)
469 fprintf(stderr
, "%s: can't allocate sufficient memory\n", myname
);
473 /* print warning if user requested more processes than we can display */
477 "%s: warning: this terminal can only display %d processes.\n",
482 /* adjust for topn == Infinity */
483 if (topn
== Infinity
)
486 * For smart terminals, infinity really means everything that can
487 * be displayed, or Largest.
488 * On dumb terminals, infinity means every process in the system!
489 * We only really want to do that if it was explicitly specified.
490 * This is always the case when "Default_TOPN != Infinity". But if
491 * topn wasn't explicitly specified and we are on a dumb terminal
492 * and the default is Infinity, then (and only then) we use
493 * "Nominal_TOPN" instead.
495 #if Default_TOPN == Infinity
496 topn
= smart_terminal
? Largest
:
497 (topn_specified
? Largest
: Nominal_TOPN
);
503 /* set header display accordingly */
504 display_header(topn
> 0);
506 /* determine interactive state */
507 if (interactive
== Maybe
)
509 interactive
= smart_terminal
;
512 /* if # of displays not specified, fill it in */
515 displays
= smart_terminal
? Infinity
: 1;
518 /* hold interrupt signals while setting up the screen and the handlers */
524 old_sigmask
= sigblock(Smask(SIGINT
) | Smask(SIGQUIT
) | Smask(SIGTSTP
));
527 (void) signal(SIGINT
, leave
);
528 (void) signal(SIGQUIT
, leave
);
529 (void) signal(SIGTSTP
, tstop
);
531 (void) signal(SIGWINCH
, winch
);
538 (void) sigsetmask(old_sigmask
);
542 fputs("....", stderr
);
543 fflush(stderr
); /* why must I do this? */
544 sleep((unsigned)(3 * warnings
));
551 * main loop -- repeat while display count is positive or while it
552 * indicates infinity (by being -1)
555 while ((displays
== -1) || (displays
-- > 0))
557 /* get the current stats */
558 get_system_info(&system_info
);
560 /* get the current set of processes */
562 get_process_info(&system_info
,
565 proc_compares
[order_index
]);
570 /* display the load averages */
571 (*d_loadave
)(system_info
.last_pid
,
572 system_info
.load_avg
);
574 /* display the current time */
575 /* this method of getting the time SHOULD be fairly portable */
577 i_uptime(&system_info
.boottime
, &curr_time
);
578 i_timeofday(&curr_time
);
580 /* display process state breakdown */
581 (*d_procstates
)(system_info
.p_total
,
582 system_info
.procstates
);
584 /* display the cpu state percentage breakdown */
585 if (dostates
) /* but not the first time */
587 (*d_cpustates
)(&system_info
);
591 /* we'll do it next time */
594 z_cpustates(&system_info
);
603 /* display memory stats */
604 (*d_memory
)(system_info
.memory
);
606 /* display swap stats */
607 (*d_swap
)(system_info
.swap
);
609 /* handle message area */
612 /* update the header area */
613 (*d_header
)(header_text
);
617 /* determine number of processes to actually display */
618 /* this number will be the smallest of: active processes,
619 number user requested, number current screen accomodates */
620 active_procs
= system_info
.P_ACTIVE
;
621 if (active_procs
> topn
)
625 if (active_procs
> max_topn
)
627 active_procs
= max_topn
;
630 /* now show the top "n" processes. */
631 for (i
= 0; i
< active_procs
; i
++)
633 (*d_process
)(i
, format_next_process(processes
, get_userid
));
641 /* do end-screen processing */
644 /* now, flush the output buffer */
645 if (fflush(stdout
) != 0)
647 new_message(MT_standout
, " Write error on stdout");
653 /* only do the rest if we have more displays to show */
656 /* switch out for new display on smart terminals */
665 d_loadave
= u_loadave
;
666 d_procstates
= u_procstates
;
667 d_cpustates
= i_cpustates
;
670 d_message
= u_message
;
672 d_process
= u_process
;
680 (void) signal(SIGALRM
, onalrm
);
681 (void) alarm((unsigned)delay
);
683 /* wait for the rest of it .... */
686 else while (no_command
)
688 /* assume valid command unless told otherwise */
691 /* set up arguments for select with timeout */
693 FD_SET(0, &readfds
); /* for standard input */
694 timeout
.tv_sec
= delay
;
703 /* move to the lower left */
707 /* default the signal handler action */
708 (void) signal(SIGTSTP
, SIG_DFL
);
710 /* unblock the signal and send ourselves one */
714 (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP
- 1)));
716 (void) kill(0, SIGTSTP
);
718 /* reset the signal handler */
719 (void) signal(SIGTSTP
, tstop
);
729 /* reascertain the screen dimensions */
732 /* tell display to resize */
733 max_topn
= display_resize();
735 /* reset the signal handler */
736 (void) signal(SIGWINCH
, winch
);
743 /* wait for either input or the end of the delay period */
744 sel_ret
= select(2, &readfds
, NULL
, NULL
, &timeout
);
745 if (sel_ret
< 0 && errno
!= EINTR
)
752 /* something to read -- clear the message area first */
755 /* now read it and convert to command strchr */
756 /* (use "change" as a temporary to hold strchr) */
757 if (read(0, &ch
, 1) != 1)
759 /* read error: either 0 or -1 */
760 new_message(MT_standout
, " Read error on stdin");
765 if ((iptr
= strchr(command_chars
, ch
)) == NULL
)
767 if (ch
!= '\r' && ch
!= '\n')
769 /* illegal command */
770 new_message(MT_standout
, " Command not understood");
777 change
= iptr
- command_chars
;
778 if (overstrike
&& change
> CMD_OSLIMIT
)
781 new_message(MT_standout
,
782 " Command cannot be handled by this terminal");
788 case CMD_redraw
: /* redraw screen */
792 case CMD_update
: /* merely update display */
793 /* is the load average high? */
794 if (system_info
.load_avg
[0] > LoadMax
)
796 /* yes, go home for visual feedback */
802 case CMD_quit
: /* quit */
807 case CMD_help1
: /* help */
812 standout("Hit any key to continue: ");
814 (void) read(0, &ch
, 1);
817 case CMD_errors
: /* show errors */
818 if (error_count() == 0)
820 new_message(MT_standout
,
821 " Currently no errors to report.");
830 standout("Hit any key to continue: ");
832 (void) read(0, &ch
, 1);
836 case CMD_number1
: /* new number */
838 new_message(MT_standout
,
839 "Number of processes to show: ");
840 newval
= readline(tempbuf1
, 8, Yes
);
843 if (newval
> max_topn
)
845 new_message(MT_standout
| MT_delayed
,
846 " This terminal can only display %d processes.",
853 /* inhibit the header */
856 else if (newval
> topn
&& topn
== 0)
858 /* redraw the header */
866 case CMD_delay
: /* new seconds delay */
867 new_message(MT_standout
, "Seconds to delay: ");
868 if ((i
= readline(tempbuf1
, 8, Yes
)) > -1)
870 if ((delay
= i
) == 0 && getuid() != 0)
878 case CMD_displays
: /* change display count */
879 new_message(MT_standout
,
880 "Displays to show (currently %s): ",
881 displays
== -1 ? "infinite" :
883 if ((i
= readline(tempbuf1
, 10, Yes
)) > 0)
894 case CMD_kill
: /* kill program */
895 new_message(0, "kill ");
896 if (readline(tempbuf2
, sizeof(tempbuf2
), No
) > 0)
898 if ((errmsg
= kill_procs(tempbuf2
)) != NULL
)
900 new_message(MT_standout
, "%s", errmsg
);
911 case CMD_renice
: /* renice program */
912 new_message(0, "renice ");
913 if (readline(tempbuf2
, sizeof(tempbuf2
), No
) > 0)
915 if ((errmsg
= renice_procs(tempbuf2
)) != NULL
)
917 new_message(MT_standout
, "%s", errmsg
);
931 new_message(MT_standout
| MT_delayed
,
932 " %sisplaying idle processes.",
933 ps
.idle
? "D" : "Not d");
938 ps
.self
= (ps
.self
== -1) ? getpid() : -1;
939 new_message(MT_standout
| MT_delayed
,
940 " %sisplaying self.",
941 (ps
.self
== -1) ? "D" : "Not d");
946 ps
.threads
= !ps
.threads
;
947 new_message(MT_standout
| MT_delayed
,
948 " %sisplaying threads.",
949 ps
.threads
? "D" : "Not d");
954 ps
.only_threads
= !ps
.only_threads
;
955 new_message(MT_standout
| MT_delayed
,
957 "Only displaying threads." :
958 "Displaying threads and processes.");
963 ps
.system
= !ps
.system
;
964 new_message(MT_standout
| MT_delayed
,
965 " %sisplaying system processes.",
966 ps
.system
? "D" : "Not d");
971 new_message(MT_standout
,
972 "Username to show: ");
973 if (readline(tempbuf2
, sizeof(tempbuf2
), No
) > 0)
975 if (tempbuf2
[0] == '+' &&
980 else if ((i
= userid(tempbuf2
)) == -1)
982 new_message(MT_standout
,
983 " %s: unknown user", tempbuf2
);
1000 new_message(MT_standout
,
1002 if (readline(tempbuf2
, sizeof(tempbuf2
), No
) > 0)
1004 if ((i
= string_index(tempbuf2
, statics
.order_names
)) == -1)
1006 new_message(MT_standout
,
1007 " %s: unrecognized sorting order", tempbuf2
);
1024 new_message(MT_standout
, " BAD CASE IN SWITCH!");
1029 /* flush out stuff that may have been written */
1044 * reset_display() - reset all the display routine pointers so that entire
1045 * screen will get redrawn.
1051 d_loadave
= i_loadave
;
1052 d_procstates
= i_procstates
;
1053 d_cpustates
= i_cpustates
;
1054 d_memory
= i_memory
;
1056 d_message
= i_message
;
1057 d_header
= i_header
;
1058 d_process
= i_process
;
1065 sigret_t
leave() /* exit under normal conditions -- INT handler */
1071 sigret_t
tstop(i
) /* SIGTSTP handler */
1080 sigret_t
winch(i
) /* SIGWINCH handler */
1089 void quit(status
) /* exit under duress */
1099 sigret_t
onalrm() /* SIGALRM handler */
1102 /* this is only used in batch mode to break out of the pause() */