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
36 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
38 unsigned pcpu; /* delta of ticks */
45 static top_status_t *top;
47 /* This structure stores some critical information from one frame to
48 the next. Used for finding deltas. */
53 static struct save_hist *prev_hist;
54 static int prev_hist_count;
55 /* static int hist_iterations; */
56 static unsigned total_pcpu;
57 /* static unsigned long total_rss; */
60 #define OPT_BATCH_MODE (option_mask32 & 0x4)
62 #if ENABLE_FEATURE_USE_TERMIOS
63 static int pid_sort(top_status_t *P, top_status_t *Q)
65 /* Buggy wrt pids with high bit set */
66 /* (linux pids are in [1..2^15-1]) */
67 return (Q->pid - P->pid);
71 static int mem_sort(top_status_t *P, top_status_t *Q)
73 /* We want to avoid unsigned->signed and truncation errors */
74 if (Q->rss < P->rss) return -1;
75 return Q->rss != P->rss; /* 0 if ==, 1 if > */
79 typedef int (*cmp_funcp)(top_status_t *P, top_status_t *Q);
81 #if !ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
83 static cmp_funcp sort_function;
87 enum { SORT_DEPTH = 3 };
89 static cmp_funcp sort_function[SORT_DEPTH];
91 static int pcpu_sort(top_status_t *P, top_status_t *Q)
93 /* Buggy wrt ticks with high bit set */
94 /* Affects only processes for which ticks overflow */
95 return (int)Q->pcpu - (int)P->pcpu;
98 static int time_sort(top_status_t *P, top_status_t *Q)
100 /* We want to avoid unsigned->signed and truncation errors */
101 if (Q->ticks < P->ticks) return -1;
102 return Q->ticks != P->ticks; /* 0 if ==, 1 if > */
105 static int mult_lvl_cmp(void* a, void* b) {
108 for (i = 0; i < SORT_DEPTH; i++) {
109 cmp_val = (*sort_function[i])(a, b);
118 unsigned long long usr,nic,sys,idle,iowait,irq,softirq,steal;
119 unsigned long long total;
120 unsigned long long busy;
122 static jiffy_counts_t jif, prev_jif;
123 static void get_jiffy_counts(void)
125 FILE* fp = xfopen("stat", "r");
127 if (fscanf(fp, "cpu %lld %lld %lld %lld %lld %lld %lld %lld",
128 &jif.usr,&jif.nic,&jif.sys,&jif.idle,
129 &jif.iowait,&jif.irq,&jif.softirq,&jif.steal) < 4) {
130 bb_error_msg_and_die("failed to read /proc/stat");
133 jif.total = jif.usr + jif.nic + jif.sys + jif.idle
134 + jif.iowait + jif.irq + jif.softirq + jif.steal;
135 /* procps 2.x does not count iowait as busy time */
136 jif.busy = jif.total - jif.idle - jif.iowait;
140 static void do_stats(void)
145 struct save_hist *new_hist;
150 new_hist = xmalloc(sizeof(struct save_hist)*ntop);
152 * Make a pass through the data to get stats.
154 /* hist_iterations = 0; */
156 for (n = 0; n < ntop; n++) {
160 * Calculate time in cur process. Time is sum of user time
164 new_hist[n].ticks = cur->ticks;
165 new_hist[n].pid = pid;
167 /* find matching entry from previous pass */
169 /* do not start at index 0, continue at last used one
170 * (brought hist_iterations from ~14000 down to 172) */
172 if (prev_hist_count) do {
173 if (prev_hist[i].pid == pid) {
174 cur->pcpu = cur->ticks - prev_hist[i].ticks;
175 total_pcpu += cur->pcpu;
178 i = (i+1) % prev_hist_count;
179 /* hist_iterations++; */
180 } while (i != last_i);
181 /* total_rss += cur->rss; */
185 * Save cur frame's information.
188 prev_hist = new_hist;
189 prev_hist_count = ntop;
191 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
194 /* display generic info (meminfo / loadavg) */
195 static unsigned long display_generic(int scr_width)
201 unsigned long total, used, mfree, shared, buffers, cached;
202 unsigned int needs_conversion = 1;
204 /* read memory info */
205 fp = xfopen("meminfo", "r");
208 * Old kernels (such as 2.4.x) had a nice summary of memory info that
209 * we could parse, however this is gone entirely in 2.6. Try parsing
210 * the old way first, and if that fails, parse each field manually.
212 * First, we read in the first line. Old kernels will have bogus
213 * strings we don't care about, whereas new kernels will start right
217 if (fscanf(fp, "MemTotal: %lu %s\n", &total, buf) != 2) {
218 fgets(buf, sizeof(buf), fp); /* skip first line */
220 fscanf(fp, "Mem: %lu %lu %lu %lu %lu %lu",
221 &total, &used, &mfree, &shared, &buffers, &cached);
224 * Revert to manual parsing, which incidentally already has the
225 * sizes in kilobytes. This should be safe for both 2.4 and
228 needs_conversion = 0;
230 fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
233 * MemShared: is no longer present in 2.6. Report this as 0,
234 * to maintain consistent behavior with normal procps.
236 if (fscanf(fp, "MemShared: %lu %s\n", &shared, buf) != 2)
239 fscanf(fp, "Buffers: %lu %s\n", &buffers, buf);
240 fscanf(fp, "Cached: %lu %s\n", &cached, buf);
242 used = total - mfree;
246 /* read load average as a string */
248 open_read_close("loadavg", buf, sizeof(buf));
249 end = strchr(buf, ' ');
250 if (end) end = strchr(end+1, ' ');
251 if (end) end = strchr(end+1, ' ');
252 if (end) *end = '\0';
254 if (needs_conversion) {
255 /* convert to kilobytes */
264 /* output memory info and load average */
265 /* clear screen & go to top */
266 if (scr_width > sizeof(scrbuf))
267 scr_width = sizeof(scrbuf);
268 snprintf(scrbuf, scr_width,
269 "Mem: %ldK used, %ldK free, %ldK shrd, %ldK buff, %ldK cached",
270 used, mfree, shared, buffers, cached);
272 printf(OPT_BATCH_MODE ? "%s\n" : "\e[H\e[J%s\n", scrbuf);
274 snprintf(scrbuf, scr_width, "Load average: %s", buf);
275 printf("%s\n", scrbuf);
281 /* display process statuses */
282 static void display_status(int count, int scr_width)
285 bits_per_int = sizeof(int)*8
288 top_status_t *s = top;
290 unsigned long total_memory = display_generic(scr_width); /* or use total_rss? */
291 unsigned pmem_shift, pmem_scale;
293 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
294 unsigned pcpu_shift, pcpu_scale;
297 /* what info of the processes is shown */
298 printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
299 " PID USER STATUS RSS PPID %CPU %MEM COMMAND");
301 sizeof( " PID USER STATUS RSS PPID %CPU %MEM C")
303 printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
304 " PID USER STATUS RSS PPID %MEM COMMAND");
306 sizeof( " PID USER STATUS RSS PPID %MEM C")
310 * MEM% = s->rss/MemTotal
312 pmem_shift = bits_per_int-11;
313 pmem_scale = 1000*(1U<<(bits_per_int-11)) / total_memory;
314 /* s->rss is in kb. we want (s->rss * pmem_scale) to never overflow */
315 while (pmem_scale >= 512) {
319 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
320 busy_jifs = jif.busy - prev_jif.busy;
321 /* This happens if there were lots of short-lived processes
322 * between two top updates (e.g. compilation) */
323 if (total_pcpu < busy_jifs) total_pcpu = busy_jifs;
326 * CPU% = s->pcpu/sum(s->pcpu) * busy_cpu_ticks/total_cpu_ticks
327 * (pcpu is delta of sys+user time between samples)
329 /* (jif.xxx - prev_jif.xxx) and s->pcpu are
330 * in 0..~64000 range (HZ*update_interval).
331 * we assume that unsigned is at least 32-bit.
334 pcpu_scale = (1000*64*(uint16_t)busy_jifs ? : 1);
335 while (pcpu_scale < (1U<<(bits_per_int-2))) {
339 pcpu_scale /= ( (uint16_t)(jif.total-prev_jif.total)*total_pcpu ? : 1);
340 /* we want (s->pcpu * pcpu_scale) to never overflow */
341 while (pcpu_scale >= 1024) {
345 /* printf(" pmem_scale=%u pcpu_scale=%u ", pmem_scale, pcpu_scale); */
347 while (count-- > 0) {
348 div_t pmem = div((s->rss*pmem_scale) >> pmem_shift, 10);
349 int col = scr_width+1;
350 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(div_t pcpu;)
352 if (s->rss >= 100*1024)
353 sprintf(rss_str_buf, "%6ldM", s->rss/1024);
355 sprintf(rss_str_buf, "%7ld", s->rss);
356 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(
357 pcpu = div((s->pcpu*pcpu_scale) >> pcpu_shift, 10);
359 col -= printf("\n%5u %-8s %s "
361 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE("%3u.%c")
363 s->pid, get_cached_username(s->uid), s->state,
364 rss_str_buf, s->ppid,
365 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(pcpu.quot, '0'+pcpu.rem,)
366 pmem.quot, '0'+pmem.rem);
368 printf("%.*s", col, s->comm);
369 /* printf(" %d/%d %lld/%lld", s->pcpu, total_pcpu,
370 jif.busy - prev_jif.busy, jif.total - prev_jif.total); */
373 /* printf(" %d", hist_iterations); */
374 putchar(OPT_BATCH_MODE ? '\n' : '\r');
379 static void clearmems(void)
381 clear_username_cache();
388 #if ENABLE_FEATURE_USE_TERMIOS
392 static struct termios initial_settings;
394 static void reset_term(void)
396 tcsetattr(0, TCSANOW, (void *) &initial_settings);
397 #if ENABLE_FEATURE_CLEAN_UP
399 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
402 #endif /* FEATURE_CLEAN_UP */
405 static void sig_catcher(int sig ATTRIBUTE_UNUSED)
410 #endif /* FEATURE_USE_TERMIOS */
413 int top_main(int argc, char **argv)
415 int count, lines, col;
416 unsigned interval = 5; /* default update rate is 5 seconds */
417 unsigned iterations = UINT_MAX; /* 2^32 iterations by default :) */
418 char *sinterval, *siterations;
419 #if ENABLE_FEATURE_USE_TERMIOS
420 struct termios new_settings;
424 #endif /* FEATURE_USE_TERMIOS */
426 /* do normal option parsing */
428 opt_complementary = "-";
429 getopt32(argc, argv, "d:n:b", &sinterval, &siterations);
430 if (option_mask32 & 0x1) interval = xatou(sinterval); // -d
431 if (option_mask32 & 0x2) iterations = xatou(siterations); // -n
432 //if (option_mask32 & 0x4) // -b
434 /* change to /proc */
436 #if ENABLE_FEATURE_USE_TERMIOS
437 tcgetattr(0, (void *) &initial_settings);
438 memcpy(&new_settings, &initial_settings, sizeof(struct termios));
439 /* unbuffered input, turn off echo */
440 new_settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHONL);
442 signal(SIGTERM, sig_catcher);
443 signal(SIGINT, sig_catcher);
444 tcsetattr(0, TCSANOW, (void *) &new_settings);
446 #endif /* FEATURE_USE_TERMIOS */
448 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
449 sort_function[0] = pcpu_sort;
450 sort_function[1] = mem_sort;
451 sort_function[2] = time_sort;
453 sort_function = mem_sort;
454 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
457 procps_status_t *p = NULL;
459 /* Default to 25 lines - 5 lines for status */
462 #if ENABLE_FEATURE_USE_TERMIOS
463 get_terminal_width_height(0, &col, &lines);
464 if (lines < 5 || col < MIN_WIDTH) {
469 #endif /* FEATURE_USE_TERMIOS */
471 /* read process IDs & status for all the processes */
472 while ((p = procps_scan(p, 0
484 top = xrealloc(top, (++ntop)*sizeof(top_status_t));
486 top[n].ppid = p->ppid;
488 top[n].ticks = p->stime + p->utime;
490 strcpy(top[n].state, p->state);
491 strcpy(top[n].comm, p->comm);
494 bb_error_msg_and_die("can't find process info in /proc");
496 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
497 if (!prev_hist_count) {
504 qsort(top, ntop, sizeof(top_status_t), (void*)mult_lvl_cmp);
506 qsort(top, ntop, sizeof(top_status_t), (void*)sort_function);
507 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
509 if (OPT_BATCH_MODE || count > ntop) {
512 /* show status for each of the processes */
513 display_status(count, col);
514 #if ENABLE_FEATURE_USE_TERMIOS
515 tv.tv_sec = interval;
519 select(1, &readfds, NULL, NULL, &tv);
520 if (FD_ISSET(0, &readfds)) {
521 if (read(0, &c, 1) <= 0) { /* signal */
524 if (c == 'q' || c == initial_settings.c_cc[VINTR])
527 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
528 sort_function[0] = mem_sort;
529 sort_function[1] = pcpu_sort;
530 sort_function[2] = time_sort;
532 sort_function = mem_sort;
535 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
537 sort_function[0] = pcpu_sort;
538 sort_function[1] = mem_sort;
539 sort_function[2] = time_sort;
542 sort_function[0] = time_sort;
543 sort_function[1] = mem_sort;
544 sort_function[2] = pcpu_sort;
548 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
549 sort_function[0] = pid_sort;
551 sort_function = pid_sort;
559 #endif /* FEATURE_USE_TERMIOS */
562 if (ENABLE_FEATURE_CLEAN_UP)