1 /* vi: set sw=4 ts=4: */
3 * A tiny 'top' utility.
5 * This is written specifically for the linux /proc/<PID>/stat(m)
8 * This reads the PIDs of all processes and their status and shows
9 * the status of processes (first ones that fit to screen) at given
13 * - At startup this changes to /proc, all the reads are then
16 * (C) Eero Tamminen <oak at welho dot com>
18 * Rewritten by Vladimir Oleynik (C) 2002 <dzo@simtreas.ru>
21 /* Original code Copyrights */
23 * Copyright (c) 1992 Branko Lankester
24 * Copyright (c) 1992 Roger Binns
25 * Copyright (C) 1994-1996 Charles L. Blake.
26 * Copyright (C) 1992-1998 Michael K. Johnson
27 * May be distributed under the conditions of the
28 * GNU Library General Public License
32 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 //#define CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE /* + 2k */
41 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
44 #include <netinet/in.h> /* htons */
48 typedef int (*cmp_t)(procps_status_t *P, procps_status_t *Q);
50 static procps_status_t *top; /* Hehe */
53 #ifdef CONFIG_FEATURE_USE_TERMIOS
54 static int pid_sort(procps_status_t *P, procps_status_t *Q)
56 return (Q->pid - P->pid);
60 static int mem_sort(procps_status_t *P, procps_status_t *Q)
62 return (int)(Q->rss - P->rss);
65 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
68 static cmp_t sort_function[sort_depth];
70 static int pcpu_sort(procps_status_t *P, procps_status_t *Q)
72 return (Q->pcpu - P->pcpu);
75 static int time_sort(procps_status_t *P, procps_status_t *Q)
77 return (int)((Q->stime + Q->utime) - (P->stime + P->utime));
80 static int mult_lvl_cmp(void* a, void* b) {
83 for (i = 0; i < sort_depth; i++) {
84 cmp_val = (*sort_function[i])(a, b);
91 /* This structure stores some critical information from one frame to
92 the next. mostly used for sorting. Added cumulative and resident fields. */
99 * Calculates percent cpu usage for each task.
102 static struct save_hist *prev_hist;
103 static int prev_hist_count;
104 /* static int hist_iterations; */
107 static unsigned total_pcpu;
108 /* static unsigned long total_rss; */
110 struct jiffy_counts {
111 unsigned long long usr,nic,sys,idle,iowait,irq,softirq,steal;
112 unsigned long long total;
113 unsigned long long busy;
115 static struct jiffy_counts jif, prev_jif;
117 static void get_jiffy_counts(void)
119 FILE* fp = bb_xfopen("stat", "r");
121 if (fscanf(fp, "cpu %lld %lld %lld %lld %lld %lld %lld %lld",
122 &jif.usr,&jif.nic,&jif.sys,&jif.idle,
123 &jif.iowait,&jif.irq,&jif.softirq,&jif.steal) < 4) {
124 bb_error_msg_and_die("failed to read 'stat'");
127 jif.total = jif.usr + jif.nic + jif.sys + jif.idle
128 + jif.iowait + jif.irq + jif.softirq + jif.steal;
129 /* procps 2.x does not count iowait as busy time */
130 jif.busy = jif.total - jif.idle - jif.iowait;
133 static void do_stats(void)
135 procps_status_t *cur;
136 int pid, total_time, i, last_i, n;
137 struct save_hist *new_hist;
142 new_hist = xmalloc(sizeof(struct save_hist)*ntop);
144 * Make a pass through the data to get stats.
146 /* hist_iterations = 0; */
148 for (n = 0; n < ntop; n++) {
152 * Calculate time in cur process. Time is sum of user time
156 total_time = cur->stime + cur->utime;
157 new_hist[n].ticks = total_time;
158 new_hist[n].pid = pid;
160 /* find matching entry from previous pass */
162 /* do not start at index 0, continue at last used one
163 * (brought hist_iterations from ~14000 down to 172) */
165 if (prev_hist_count) do {
166 if (prev_hist[i].pid == pid) {
167 cur->pcpu = total_time - prev_hist[i].ticks;
170 i = (i+1) % prev_hist_count;
171 /* hist_iterations++; */
172 } while (i != last_i);
173 total_pcpu += cur->pcpu;
174 /* total_rss += cur->rss; */
178 * Save cur frame's information.
181 prev_hist = new_hist;
182 prev_hist_count = ntop;
185 static cmp_t sort_function;
186 #endif /* CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE */
188 /* display generic info (meminfo / loadavg) */
189 static unsigned long display_generic(int scr_width)
195 unsigned long total, used, mfree, shared, buffers, cached;
196 unsigned int needs_conversion = 1;
198 /* read memory info */
199 fp = bb_xfopen("meminfo", "r");
202 * Old kernels (such as 2.4.x) had a nice summary of memory info that
203 * we could parse, however this is gone entirely in 2.6. Try parsing
204 * the old way first, and if that fails, parse each field manually.
206 * First, we read in the first line. Old kernels will have bogus
207 * strings we don't care about, whereas new kernels will start right
211 if (fscanf(fp, "MemTotal: %lu %s\n", &total, buf) != 2) {
212 fgets(buf, sizeof(buf), fp); /* skip first line */
214 fscanf(fp, "Mem: %lu %lu %lu %lu %lu %lu",
215 &total, &used, &mfree, &shared, &buffers, &cached);
218 * Revert to manual parsing, which incidentally already has the
219 * sizes in kilobytes. This should be safe for both 2.4 and
222 needs_conversion = 0;
224 fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
227 * MemShared: is no longer present in 2.6. Report this as 0,
228 * to maintain consistent behavior with normal procps.
230 if (fscanf(fp, "MemShared: %lu %s\n", &shared, buf) != 2)
233 fscanf(fp, "Buffers: %lu %s\n", &buffers, buf);
234 fscanf(fp, "Cached: %lu %s\n", &cached, buf);
236 used = total - mfree;
240 /* read load average as a string */
241 fp = bb_xfopen("loadavg", "r");
243 fgets(buf, sizeof(buf), fp);
244 end = strchr(buf, ' ');
245 if (end) end = strchr(end+1, ' ');
246 if (end) end = strchr(end+1, ' ');
247 if (end) *end = '\0';
250 if (needs_conversion) {
251 /* convert to kilobytes */
260 /* output memory info and load average */
261 /* clear screen & go to top */
262 if (scr_width > sizeof(scrbuf))
263 scr_width = sizeof(scrbuf);
264 snprintf(scrbuf, scr_width,
265 "Mem: %ldK used, %ldK free, %ldK shrd, %ldK buff, %ldK cached",
266 used, mfree, shared, buffers, cached);
267 printf("\e[H\e[J%s\n", scrbuf);
268 snprintf(scrbuf, scr_width,
269 "Load average: %s (Status: S=sleeping R=running, W=waiting)", buf);
270 printf("%s\n", scrbuf);
276 /* display process statuses */
277 static void display_status(int count, int scr_width)
280 bits_per_int = sizeof(int)*8
283 procps_status_t *s = top;
285 unsigned long total_memory = display_generic(scr_width); /* or use total_rss? */
286 unsigned pmem_shift, pmem_scale;
288 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
289 unsigned pcpu_shift, pcpu_scale;
291 /* what info of the processes is shown */
292 printf("\e[7m%.*s\e[0m", scr_width,
293 " PID USER STATUS RSS PPID %CPU %MEM COMMAND");
295 sizeof( " PID USER STATUS RSS PPID %CPU %MEM C")
297 printf("\e[7m%.*s\e[0m", scr_width,
298 " PID USER STATUS RSS PPID %MEM COMMAND");
300 sizeof( " PID USER STATUS RSS PPID %MEM C")
304 * MEM% = s->rss/MemTotal
306 pmem_shift = bits_per_int-11;
307 pmem_scale = 1000*(1U<<(bits_per_int-11)) / total_memory;
308 /* s->rss is in kb. we want (s->rss * pmem_scale) to never overflow */
309 while (pmem_scale >= 512) {
313 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
315 * CPU% = s->pcpu/sum(s->pcpu) * busy_cpu_ticks/total_cpu_ticks
316 * (pcpu is delta of sys+user time between samples)
318 /* (jif.xxx - prev_jif.xxx) and s->pcpu are
319 * in 0..~64000 range (HZ*update_interval).
320 * we assume that unsigned is at least 32-bit.
323 pcpu_scale = (1000*64*(uint16_t)(jif.busy-prev_jif.busy) ? : 1);
324 while (pcpu_scale < (1U<<(bits_per_int-2))) {
328 pcpu_scale /= ( (uint16_t)(jif.total-prev_jif.total)*total_pcpu ? : 1);
329 /* we want (s->pcpu * pcpu_scale) to never overflow */
330 while (pcpu_scale >= 1024) {
334 /* printf(" pmem_scale=%u pcpu_scale=%u ", pmem_scale, pcpu_scale); */
338 div_t pmem = div( (s->rss*pmem_scale) >> pmem_shift, 10);
339 int col = scr_width+1;
340 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(div_t pcpu;)
342 if (s->rss >= 100*1024)
343 sprintf(rss_str_buf, "%6ldM", s->rss/1024);
345 sprintf(rss_str_buf, "%7ld", s->rss);
346 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(pcpu = div((s->pcpu*pcpu_scale) >> pcpu_shift, 10);)
347 col -= printf("\n%5d %-8s %s %s%6d%3u.%c" \
348 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE("%3u.%c") " ",
349 s->pid, s->user, s->state, rss_str_buf, s->ppid,
350 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(pcpu.quot, '0'+pcpu.rem,)
351 pmem.quot, '0'+pmem.rem);
353 printf("%.*s", col, s->short_cmd);
354 /* printf(" %d/%d %lld/%lld", s->pcpu, total_pcpu,
355 jif.busy - prev_jif.busy, jif.total - prev_jif.total); */
358 /* printf(" %d", hist_iterations); */
363 static void clearmems(void)
370 #ifdef CONFIG_FEATURE_USE_TERMIOS
375 static struct termios initial_settings;
377 static void reset_term(void)
379 tcsetattr(0, TCSANOW, (void *) &initial_settings);
380 #ifdef CONFIG_FEATURE_CLEAN_UP
382 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
385 #endif /* CONFIG_FEATURE_CLEAN_UP */
388 static void sig_catcher(int sig ATTRIBUTE_UNUSED)
392 #endif /* CONFIG_FEATURE_USE_TERMIOS */
395 int top_main(int argc, char **argv)
397 int opt, interval, lines, col;
399 #ifdef CONFIG_FEATURE_USE_TERMIOS
400 struct termios new_settings;
405 #endif /* CONFIG_FEATURE_USE_TERMIOS */
407 /* do normal option parsing */
408 opt = bb_getopt_ulflags(argc, argv, "d:", &sinterval);
410 interval = atoi(sinterval);
412 /* Default update rate is 5 seconds */
416 /* change to /proc */
418 #ifdef CONFIG_FEATURE_USE_TERMIOS
419 tcgetattr(0, (void *) &initial_settings);
420 memcpy(&new_settings, &initial_settings, sizeof(struct termios));
421 new_settings.c_lflag &= ~(ISIG | ICANON); /* unbuffered input */
422 /* Turn off echoing */
423 new_settings.c_lflag &= ~(ECHO | ECHONL);
425 signal(SIGTERM, sig_catcher);
426 sigaction(SIGTERM, (struct sigaction *) 0, &sa);
427 sa.sa_flags |= SA_RESTART;
428 sa.sa_flags &= ~SA_INTERRUPT;
429 sigaction(SIGTERM, &sa, (struct sigaction *) 0);
430 sigaction(SIGINT, &sa, (struct sigaction *) 0);
431 tcsetattr(0, TCSANOW, (void *) &new_settings);
433 #endif /* CONFIG_FEATURE_USE_TERMIOS */
435 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
436 sort_function[0] = pcpu_sort;
437 sort_function[1] = mem_sort;
438 sort_function[2] = time_sort;
440 sort_function = mem_sort;
441 #endif /* CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE */
446 /* Default to 25 lines - 5 lines for status */
449 #ifdef CONFIG_FEATURE_USE_TERMIOS
450 get_terminal_width_height(0, &col, &lines);
451 if (lines < 5 || col < MIN_WIDTH) {
456 #endif /* CONFIG_FEATURE_USE_TERMIOS */
458 /* read process IDs & status for all the processes */
459 while ((p = procps_scan(0)) != 0) {
462 top = xrealloc(top, (++ntop)*sizeof(procps_status_t));
463 memcpy(top + n, p, sizeof(procps_status_t));
466 bb_error_msg_and_die("Can't find process info in /proc");
468 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
469 if (!prev_hist_count) {
476 qsort(top, ntop, sizeof(procps_status_t), (void*)mult_lvl_cmp);
478 qsort(top, ntop, sizeof(procps_status_t), (void*)sort_function);
479 #endif /* CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE */
484 /* show status for each of the processes */
485 display_status(opt, col);
486 #ifdef CONFIG_FEATURE_USE_TERMIOS
487 tv.tv_sec = interval;
491 select(1, &readfds, NULL, NULL, &tv);
492 if (FD_ISSET(0, &readfds)) {
493 if (read(0, &c, 1) <= 0) { /* signal */
496 if (c == 'q' || c == initial_settings.c_cc[VINTR])
499 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
500 sort_function[0] = mem_sort;
501 sort_function[1] = pcpu_sort;
502 sort_function[2] = time_sort;
504 sort_function = mem_sort;
507 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
509 sort_function[0] = pcpu_sort;
510 sort_function[1] = mem_sort;
511 sort_function[2] = time_sort;
514 sort_function[0] = time_sort;
515 sort_function[1] = mem_sort;
516 sort_function[2] = pcpu_sort;
520 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
521 sort_function[0] = pid_sort;
523 sort_function = pid_sort;
529 #endif /* CONFIG_FEATURE_USE_TERMIOS */
532 if (ENABLE_FEATURE_CLEAN_UP)