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
34 typedef struct top_status_t {
36 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
38 unsigned pcpu; /* delta of ticks */
46 typedef struct jiffy_counts_t {
47 unsigned long long usr,nic,sys,idle,iowait,irq,softirq,steal;
48 unsigned long long total;
49 unsigned long long busy;
52 /* This structure stores some critical information from one frame to
53 the next. Used for finding deltas. */
54 typedef struct save_hist {
59 typedef int (*cmp_funcp)(top_status_t *P, top_status_t *Q);
61 enum { SORT_DEPTH = 3 };
66 #if ENABLE_FEATURE_USE_TERMIOS
67 struct termios initial_settings;
69 #if !ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
70 cmp_funcp sort_function;
72 cmp_funcp sort_function[SORT_DEPTH];
73 struct save_hist *prev_hist;
75 jiffy_counts_t jif, prev_jif;
76 /* int hist_iterations; */
78 /* unsigned long total_vsz; */
81 #define G (*(struct globals*)&bb_common_bufsiz1)
83 #define ntop (G.ntop )
84 #if ENABLE_FEATURE_USE_TERMIOS
85 #define initial_settings (G. initial_settings )
87 #define sort_function (G.sort_function )
88 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
89 #define prev_hist (G.prev_hist )
90 #define prev_hist_count (G.prev_hist_count )
92 #define prev_jif (G.prev_jif )
93 #define total_pcpu (G.total_pcpu )
96 #define OPT_BATCH_MODE (option_mask32 & 0x4)
99 #if ENABLE_FEATURE_USE_TERMIOS
100 static int pid_sort(top_status_t *P, top_status_t *Q)
102 /* Buggy wrt pids with high bit set */
103 /* (linux pids are in [1..2^15-1]) */
104 return (Q->pid - P->pid);
108 static int mem_sort(top_status_t *P, top_status_t *Q)
110 /* We want to avoid unsigned->signed and truncation errors */
111 if (Q->vsz < P->vsz) return -1;
112 return Q->vsz != P->vsz; /* 0 if ==, 1 if > */
116 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
118 static int pcpu_sort(top_status_t *P, top_status_t *Q)
120 /* Buggy wrt ticks with high bit set */
121 /* Affects only processes for which ticks overflow */
122 return (int)Q->pcpu - (int)P->pcpu;
125 static int time_sort(top_status_t *P, top_status_t *Q)
127 /* We want to avoid unsigned->signed and truncation errors */
128 if (Q->ticks < P->ticks) return -1;
129 return Q->ticks != P->ticks; /* 0 if ==, 1 if > */
132 static int mult_lvl_cmp(void* a, void* b)
136 for (i = 0; i < SORT_DEPTH; i++) {
137 cmp_val = (*sort_function[i])(a, b);
145 static void get_jiffy_counts(void)
147 FILE* fp = xfopen("stat", "r");
149 if (fscanf(fp, "cpu %lld %lld %lld %lld %lld %lld %lld %lld",
150 &jif.usr,&jif.nic,&jif.sys,&jif.idle,
151 &jif.iowait,&jif.irq,&jif.softirq,&jif.steal) < 4) {
152 bb_error_msg_and_die("failed to read /proc/stat");
155 jif.total = jif.usr + jif.nic + jif.sys + jif.idle
156 + jif.iowait + jif.irq + jif.softirq + jif.steal;
157 /* procps 2.x does not count iowait as busy time */
158 jif.busy = jif.total - jif.idle - jif.iowait;
162 static void do_stats(void)
167 struct save_hist *new_hist;
172 new_hist = xmalloc(sizeof(struct save_hist)*ntop);
174 * Make a pass through the data to get stats.
176 /* hist_iterations = 0; */
178 for (n = 0; n < ntop; n++) {
182 * Calculate time in cur process. Time is sum of user time
186 new_hist[n].ticks = cur->ticks;
187 new_hist[n].pid = pid;
189 /* find matching entry from previous pass */
191 /* do not start at index 0, continue at last used one
192 * (brought hist_iterations from ~14000 down to 172) */
194 if (prev_hist_count) do {
195 if (prev_hist[i].pid == pid) {
196 cur->pcpu = cur->ticks - prev_hist[i].ticks;
197 total_pcpu += cur->pcpu;
200 i = (i+1) % prev_hist_count;
201 /* hist_iterations++; */
202 } while (i != last_i);
203 /* total_vsz += cur->vsz; */
207 * Save cur frame's information.
210 prev_hist = new_hist;
211 prev_hist_count = ntop;
213 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
215 #if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS && ENABLE_FEATURE_TOP_DECIMALS
216 /* formats 7 char string (8 with terminating NUL) */
217 static char *fmt_100percent_8(char pbuf[8], unsigned value, unsigned total)
220 if (value >= total) { /* 100% ? */
221 strcpy(pbuf, " 100% ");
224 /* else generate " [N/space]N.N% " string */
225 value = 1000 * value / total;
229 pbuf[1] = t ? t + '0' : ' ';
230 pbuf[2] = '0' + (value / 10);
232 pbuf[4] = '0' + (value % 10);
240 /* display generic info (meminfo / loadavg) */
241 static unsigned long display_generic(int scr_width)
246 unsigned long total, used, mfree, shared, buffers, cached;
247 #if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS
251 /* read memory info */
252 fp = xfopen("meminfo", "r");
255 * Old kernels (such as 2.4.x) had a nice summary of memory info that
256 * we could parse, however this is gone entirely in 2.6. Try parsing
257 * the old way first, and if that fails, parse each field manually.
259 * First, we read in the first line. Old kernels will have bogus
260 * strings we don't care about, whereas new kernels will start right
264 if (fscanf(fp, "MemTotal: %lu %s\n", &total, buf) != 2) {
265 fgets(buf, sizeof(buf), fp); /* skip first line */
267 fscanf(fp, "Mem: %lu %lu %lu %lu %lu %lu",
268 &total, &used, &mfree, &shared, &buffers, &cached);
269 /* convert to kilobytes */
278 * Revert to manual parsing, which incidentally already has the
279 * sizes in kilobytes. This should be safe for both 2.4 and
283 fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
286 * MemShared: is no longer present in 2.6. Report this as 0,
287 * to maintain consistent behavior with normal procps.
289 if (fscanf(fp, "MemShared: %lu %s\n", &shared, buf) != 2)
292 fscanf(fp, "Buffers: %lu %s\n", &buffers, buf);
293 fscanf(fp, "Cached: %lu %s\n", &cached, buf);
295 used = total - mfree;
299 /* output memory info */
300 if (scr_width > sizeof(scrbuf))
301 scr_width = sizeof(scrbuf);
302 snprintf(scrbuf, scr_width,
303 "Mem: %luK used, %luK free, %luK shrd, %luK buff, %luK cached",
304 used, mfree, shared, buffers, cached);
305 /* clear screen & go to top */
306 printf(OPT_BATCH_MODE ? "%s\n" : "\e[H\e[J%s\n", scrbuf);
308 #if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS
310 * xxx% = (jif.xxx - prev_jif.xxx) / (jif.total - prev_jif.total) * 100%
312 /* using (unsigned) casts to make operations cheaper */
313 total_diff = ((unsigned)(jif.total - prev_jif.total) ? : 1);
314 #if ENABLE_FEATURE_TOP_DECIMALS
315 /* Generated code is approx +0.3k */
316 #define CALC_STAT(xxx) char xxx[8]
317 #define SHOW_STAT(xxx) fmt_100percent_8(xxx, (unsigned)(jif.xxx - prev_jif.xxx), total_diff)
320 #define CALC_STAT(xxx) unsigned xxx = 100 * (unsigned)(jif.xxx - prev_jif.xxx) / total_diff
321 #define SHOW_STAT(xxx) xxx
324 { /* need block: CALC_STAT are declarations */
334 snprintf(scrbuf, scr_width,
335 /* Barely fits in 79 chars when in "decimals" mode. */
336 "CPU:"FMT"usr"FMT"sys"FMT"nice"FMT"idle"FMT"io"FMT"irq"FMT"softirq",
337 SHOW_STAT(usr), SHOW_STAT(sys), SHOW_STAT(nic), SHOW_STAT(idle),
338 SHOW_STAT(iowait), SHOW_STAT(irq), SHOW_STAT(softirq)
339 //, SHOW_STAT(steal) - what is this 'steal' thing?
340 // I doubt anyone wants to know it
349 /* read load average as a string */
351 open_read_close("loadavg", buf, sizeof("N.NN N.NN N.NN")-1);
352 buf[sizeof("N.NN N.NN N.NN")-1] = '\0';
353 snprintf(scrbuf, scr_width, "Load average: %s", buf);
359 /* display process statuses */
360 static void display_status(int count, int scr_width)
363 BITS_PER_INT = sizeof(int)*8
366 top_status_t *s = top;
368 unsigned long total_memory = display_generic(scr_width); /* or use total_vsz? */
369 /* xxx_shift and xxx_scale variables allow us to replace
370 * expensive divides with multiply and shift */
371 unsigned pmem_shift, pmem_scale, pmem_half;
372 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
373 unsigned pcpu_shift, pcpu_scale, pcpu_half;
376 /* what info of the processes is shown */
377 printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
378 " PID PPID USER STAT VSZ %MEM %CPU COMMAND");
380 sizeof( " PID PPID USER STAT VSZ %MEM %CPU C")
383 /* !CPU_USAGE_PERCENTAGE */
384 printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
385 " PID PPID USER STAT VSZ %MEM COMMAND");
387 sizeof( " PID PPID USER STAT VSZ %MEM C")
390 #if ENABLE_FEATURE_TOP_DECIMALS
392 #define CALC_STAT(name, val) div_t name = div((val), 10)
393 #define SHOW_STAT(name) name.quot, '0'+name.rem
397 #define CALC_STAT(name, val) unsigned name = (val)
398 #define SHOW_STAT(name) name
402 * MEM% = s->vsz/MemTotal
404 pmem_shift = BITS_PER_INT-11;
405 pmem_scale = UPSCALE*(1U<<(BITS_PER_INT-11)) / total_memory;
406 /* s->vsz is in kb. we want (s->vsz * pmem_scale) to never overflow */
407 while (pmem_scale >= 512) {
411 pmem_half = (1U << pmem_shift) / (ENABLE_FEATURE_TOP_DECIMALS? 20 : 2);
412 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
413 busy_jifs = jif.busy - prev_jif.busy;
414 /* This happens if there were lots of short-lived processes
415 * between two top updates (e.g. compilation) */
416 if (total_pcpu < busy_jifs) total_pcpu = busy_jifs;
419 * CPU% = s->pcpu/sum(s->pcpu) * busy_cpu_ticks/total_cpu_ticks
420 * (pcpu is delta of sys+user time between samples)
422 /* (jif.xxx - prev_jif.xxx) and s->pcpu are
423 * in 0..~64000 range (HZ*update_interval).
424 * we assume that unsigned is at least 32-bit.
427 pcpu_scale = (UPSCALE*64*(uint16_t)busy_jifs ? : 1);
428 while (pcpu_scale < (1U<<(BITS_PER_INT-2))) {
432 pcpu_scale /= ( (uint16_t)(jif.total-prev_jif.total)*total_pcpu ? : 1);
433 /* we want (s->pcpu * pcpu_scale) to never overflow */
434 while (pcpu_scale >= 1024) {
438 pcpu_half = (1U << pcpu_shift) / (ENABLE_FEATURE_TOP_DECIMALS? 20 : 2);
439 /* printf(" pmem_scale=%u pcpu_scale=%u ", pmem_scale, pcpu_scale); */
442 /* Ok, all prelim data is ready, go thru the list */
443 while (count-- > 0) {
445 CALC_STAT(pmem, (s->vsz*pmem_scale + pmem_half) >> pmem_shift);
446 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
447 CALC_STAT(pcpu, (s->pcpu*pcpu_scale + pcpu_half) >> pcpu_shift);
450 if (s->vsz >= 100*1024)
451 sprintf(vsz_str_buf, "%6ldm", s->vsz/1024);
453 sprintf(vsz_str_buf, "%7ld", s->vsz);
454 // PID PPID USER STAT VSZ %MEM [%CPU] COMMAND
455 col -= printf("\n" "%5u%6u %-8.8s %s%s" FMT
456 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
460 s->pid, s->ppid, get_cached_username(s->uid),
461 s->state, vsz_str_buf,
463 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
469 read_cmdline(buf, col, s->pid, s->comm);
472 /* printf(" %d/%d %lld/%lld", s->pcpu, total_pcpu,
473 jif.busy - prev_jif.busy, jif.total - prev_jif.total); */
476 /* printf(" %d", hist_iterations); */
477 putchar(OPT_BATCH_MODE ? '\n' : '\r');
486 static void clearmems(void)
488 clear_username_cache();
495 #if ENABLE_FEATURE_USE_TERMIOS
499 static void reset_term(void)
501 tcsetattr(0, TCSANOW, (void *) &initial_settings);
502 #if ENABLE_FEATURE_CLEAN_UP
504 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
507 #endif /* FEATURE_CLEAN_UP */
510 static void sig_catcher(int sig ATTRIBUTE_UNUSED)
515 #endif /* FEATURE_USE_TERMIOS */
518 int top_main(int argc, char **argv);
519 int top_main(int argc, char **argv)
521 int count, lines, col;
523 int iterations = -1; /* infinite */
524 char *sinterval, *siterations;
525 #if ENABLE_FEATURE_USE_TERMIOS
526 struct termios new_settings;
527 struct pollfd pfd[1];
531 pfd[0].events = POLLIN;
532 #endif /* FEATURE_USE_TERMIOS */
534 interval = 5; /* default update rate is 5 seconds */
536 /* do normal option parsing */
537 opt_complementary = "-";
538 getopt32(argv, "d:n:b", &sinterval, &siterations);
539 if (option_mask32 & 0x1) {
540 /* Need to limit it to not overflow poll timeout */
541 interval = xatou16(sinterval); // -d
543 if (option_mask32 & 0x2)
544 iterations = xatoi_u(siterations); // -n
545 //if (option_mask32 & 0x4) // -b
547 /* change to /proc */
549 #if ENABLE_FEATURE_USE_TERMIOS
550 tcgetattr(0, (void *) &initial_settings);
551 memcpy(&new_settings, &initial_settings, sizeof(struct termios));
552 /* unbuffered input, turn off echo */
553 new_settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHONL);
555 signal(SIGTERM, sig_catcher);
556 signal(SIGINT, sig_catcher);
557 tcsetattr(0, TCSANOW, (void *) &new_settings);
559 #endif /* FEATURE_USE_TERMIOS */
561 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
562 sort_function[0] = pcpu_sort;
563 sort_function[1] = mem_sort;
564 sort_function[2] = time_sort;
566 sort_function = mem_sort;
567 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
570 procps_status_t *p = NULL;
572 /* Default to 25 lines - 5 lines for status */
573 lines = 24 - 3 USE_FEATURE_TOP_CPU_GLOBAL_PERCENTS( - 1);
575 #if ENABLE_FEATURE_USE_TERMIOS
576 get_terminal_width_height(0, &col, &lines);
577 if (lines < 5 || col < MIN_WIDTH) {
581 lines -= 3 USE_FEATURE_TOP_CPU_GLOBAL_PERCENTS( + 1);
582 #endif /* FEATURE_USE_TERMIOS */
584 /* read process IDs & status for all the processes */
585 while ((p = procps_scan(p, 0
596 top = xrealloc(top, (++ntop) * sizeof(*top));
598 top[n].ppid = p->ppid;
600 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
601 top[n].ticks = p->stime + p->utime;
604 strcpy(top[n].state, p->state);
605 strcpy(top[n].comm, p->comm);
608 bb_error_msg_and_die("no process info in /proc");
610 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
611 if (!prev_hist_count) {
618 /* TODO: we don't need to sort all 10000 processes, we need to find top 24! */
619 qsort(top, ntop, sizeof(top_status_t), (void*)mult_lvl_cmp);
621 qsort(top, ntop, sizeof(top_status_t), (void*)sort_function);
622 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
624 if (OPT_BATCH_MODE || count > ntop) {
627 /* show status for each of the processes */
628 display_status(count, col);
629 #if ENABLE_FEATURE_USE_TERMIOS
630 if (poll(pfd, 1, interval * 1000) != 0) {
631 if (read(0, &c, 1) != 1) /* signal */
633 if (c == 'q' || c == initial_settings.c_cc[VINTR])
636 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
637 sort_function[0] = mem_sort;
638 sort_function[1] = pcpu_sort;
639 sort_function[2] = time_sort;
641 sort_function = mem_sort;
644 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
646 sort_function[0] = pcpu_sort;
647 sort_function[1] = mem_sort;
648 sort_function[2] = time_sort;
651 sort_function[0] = time_sort;
652 sort_function[1] = mem_sort;
653 sort_function[2] = pcpu_sort;
657 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
658 sort_function[0] = pid_sort;
660 sort_function = pid_sort;
664 if (iterations >= 0 && !--iterations)
668 #endif /* FEATURE_USE_TERMIOS */
671 if (ENABLE_FEATURE_CLEAN_UP)