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 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
54 static struct save_hist *prev_hist;
55 static int prev_hist_count;
56 /* static int hist_iterations; */
57 static unsigned total_pcpu;
58 /* static unsigned long total_vsz; */
61 #define OPT_BATCH_MODE (option_mask32 & 0x4)
63 #if ENABLE_FEATURE_USE_TERMIOS
64 static int pid_sort(top_status_t *P, top_status_t *Q)
66 /* Buggy wrt pids with high bit set */
67 /* (linux pids are in [1..2^15-1]) */
68 return (Q->pid - P->pid);
72 static int mem_sort(top_status_t *P, top_status_t *Q)
74 /* We want to avoid unsigned->signed and truncation errors */
75 if (Q->vsz < P->vsz) return -1;
76 return Q->vsz != P->vsz; /* 0 if ==, 1 if > */
80 typedef int (*cmp_funcp)(top_status_t *P, top_status_t *Q);
82 #if !ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
84 static cmp_funcp sort_function;
88 enum { SORT_DEPTH = 3 };
90 static cmp_funcp sort_function[SORT_DEPTH];
92 static int pcpu_sort(top_status_t *P, top_status_t *Q)
94 /* Buggy wrt ticks with high bit set */
95 /* Affects only processes for which ticks overflow */
96 return (int)Q->pcpu - (int)P->pcpu;
99 static int time_sort(top_status_t *P, top_status_t *Q)
101 /* We want to avoid unsigned->signed and truncation errors */
102 if (Q->ticks < P->ticks) return -1;
103 return Q->ticks != P->ticks; /* 0 if ==, 1 if > */
106 static int mult_lvl_cmp(void* a, void* b) {
109 for (i = 0; i < SORT_DEPTH; i++) {
110 cmp_val = (*sort_function[i])(a, b);
119 unsigned long long usr,nic,sys,idle,iowait,irq,softirq,steal;
120 unsigned long long total;
121 unsigned long long busy;
123 static jiffy_counts_t jif, prev_jif;
124 static void get_jiffy_counts(void)
126 FILE* fp = xfopen("stat", "r");
128 if (fscanf(fp, "cpu %lld %lld %lld %lld %lld %lld %lld %lld",
129 &jif.usr,&jif.nic,&jif.sys,&jif.idle,
130 &jif.iowait,&jif.irq,&jif.softirq,&jif.steal) < 4) {
131 bb_error_msg_and_die("failed to read /proc/stat");
134 jif.total = jif.usr + jif.nic + jif.sys + jif.idle
135 + jif.iowait + jif.irq + jif.softirq + jif.steal;
136 /* procps 2.x does not count iowait as busy time */
137 jif.busy = jif.total - jif.idle - jif.iowait;
141 static void do_stats(void)
146 struct save_hist *new_hist;
151 new_hist = xmalloc(sizeof(struct save_hist)*ntop);
153 * Make a pass through the data to get stats.
155 /* hist_iterations = 0; */
157 for (n = 0; n < ntop; n++) {
161 * Calculate time in cur process. Time is sum of user time
165 new_hist[n].ticks = cur->ticks;
166 new_hist[n].pid = pid;
168 /* find matching entry from previous pass */
170 /* do not start at index 0, continue at last used one
171 * (brought hist_iterations from ~14000 down to 172) */
173 if (prev_hist_count) do {
174 if (prev_hist[i].pid == pid) {
175 cur->pcpu = cur->ticks - prev_hist[i].ticks;
176 total_pcpu += cur->pcpu;
179 i = (i+1) % prev_hist_count;
180 /* hist_iterations++; */
181 } while (i != last_i);
182 /* total_vsz += cur->vsz; */
186 * Save cur frame's information.
189 prev_hist = new_hist;
190 prev_hist_count = ntop;
192 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
195 /* display generic info (meminfo / loadavg) */
196 static unsigned long display_generic(int scr_width)
202 unsigned long total, used, mfree, shared, buffers, cached;
203 unsigned int needs_conversion = 1;
205 /* read memory info */
206 fp = xfopen("meminfo", "r");
209 * Old kernels (such as 2.4.x) had a nice summary of memory info that
210 * we could parse, however this is gone entirely in 2.6. Try parsing
211 * the old way first, and if that fails, parse each field manually.
213 * First, we read in the first line. Old kernels will have bogus
214 * strings we don't care about, whereas new kernels will start right
218 if (fscanf(fp, "MemTotal: %lu %s\n", &total, buf) != 2) {
219 fgets(buf, sizeof(buf), fp); /* skip first line */
221 fscanf(fp, "Mem: %lu %lu %lu %lu %lu %lu",
222 &total, &used, &mfree, &shared, &buffers, &cached);
225 * Revert to manual parsing, which incidentally already has the
226 * sizes in kilobytes. This should be safe for both 2.4 and
229 needs_conversion = 0;
231 fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
234 * MemShared: is no longer present in 2.6. Report this as 0,
235 * to maintain consistent behavior with normal procps.
237 if (fscanf(fp, "MemShared: %lu %s\n", &shared, buf) != 2)
240 fscanf(fp, "Buffers: %lu %s\n", &buffers, buf);
241 fscanf(fp, "Cached: %lu %s\n", &cached, buf);
243 used = total - mfree;
247 /* read load average as a string */
249 open_read_close("loadavg", buf, sizeof(buf));
250 end = strchr(buf, ' ');
251 if (end) end = strchr(end+1, ' ');
252 if (end) end = strchr(end+1, ' ');
253 if (end) *end = '\0';
255 if (needs_conversion) {
256 /* convert to kilobytes */
265 /* output memory info and load average */
266 /* clear screen & go to top */
267 if (scr_width > sizeof(scrbuf))
268 scr_width = sizeof(scrbuf);
269 snprintf(scrbuf, scr_width,
270 "Mem: %ldK used, %ldK free, %ldK shrd, %ldK buff, %ldK cached",
271 used, mfree, shared, buffers, cached);
273 printf(OPT_BATCH_MODE ? "%s\n" : "\e[H\e[J%s\n", scrbuf);
275 snprintf(scrbuf, scr_width, "Load average: %s", buf);
276 printf("%s\n", scrbuf);
282 /* display process statuses */
283 static void display_status(int count, int scr_width)
286 bits_per_int = sizeof(int)*8
289 top_status_t *s = top;
291 unsigned long total_memory = display_generic(scr_width); /* or use total_vsz? */
292 unsigned pmem_shift, pmem_scale;
294 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
295 unsigned pcpu_shift, pcpu_scale;
298 /* what info of the processes is shown */
299 printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
300 " PID USER STATUS VSZ PPID %CPU %MEM COMMAND");
302 sizeof( " PID USER STATUS VSZ PPID %CPU %MEM C")
304 printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
305 " PID USER STATUS VSZ PPID %MEM COMMAND");
307 sizeof( " PID USER STATUS VSZ PPID %MEM C")
311 * MEM% = s->vsz/MemTotal
313 pmem_shift = bits_per_int-11;
314 pmem_scale = 1000*(1U<<(bits_per_int-11)) / total_memory;
315 /* s->vsz is in kb. we want (s->vsz * pmem_scale) to never overflow */
316 while (pmem_scale >= 512) {
320 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
321 busy_jifs = jif.busy - prev_jif.busy;
322 /* This happens if there were lots of short-lived processes
323 * between two top updates (e.g. compilation) */
324 if (total_pcpu < busy_jifs) total_pcpu = busy_jifs;
327 * CPU% = s->pcpu/sum(s->pcpu) * busy_cpu_ticks/total_cpu_ticks
328 * (pcpu is delta of sys+user time between samples)
330 /* (jif.xxx - prev_jif.xxx) and s->pcpu are
331 * in 0..~64000 range (HZ*update_interval).
332 * we assume that unsigned is at least 32-bit.
335 pcpu_scale = (1000*64*(uint16_t)busy_jifs ? : 1);
336 while (pcpu_scale < (1U<<(bits_per_int-2))) {
340 pcpu_scale /= ( (uint16_t)(jif.total-prev_jif.total)*total_pcpu ? : 1);
341 /* we want (s->pcpu * pcpu_scale) to never overflow */
342 while (pcpu_scale >= 1024) {
346 /* printf(" pmem_scale=%u pcpu_scale=%u ", pmem_scale, pcpu_scale); */
348 while (count-- > 0) {
349 div_t pmem = div((s->vsz*pmem_scale) >> pmem_shift, 10);
350 int col = scr_width+1;
351 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(div_t pcpu;)
353 if (s->vsz >= 100*1024)
354 sprintf(vsz_str_buf, "%6ldM", s->vsz/1024);
356 sprintf(vsz_str_buf, "%7ld", s->vsz);
357 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(
358 pcpu = div((s->pcpu*pcpu_scale) >> pcpu_shift, 10);
360 col -= printf("\n%5u %-8s %s "
362 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE("%3u.%c")
364 s->pid, get_cached_username(s->uid), s->state,
365 vsz_str_buf, s->ppid,
366 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(pcpu.quot, '0'+pcpu.rem,)
367 pmem.quot, '0'+pmem.rem);
369 printf("%.*s", col, s->comm);
370 /* printf(" %d/%d %lld/%lld", s->pcpu, total_pcpu,
371 jif.busy - prev_jif.busy, jif.total - prev_jif.total); */
374 /* printf(" %d", hist_iterations); */
375 putchar(OPT_BATCH_MODE ? '\n' : '\r');
380 static void clearmems(void)
382 clear_username_cache();
389 #if ENABLE_FEATURE_USE_TERMIOS
393 static struct termios initial_settings;
395 static void reset_term(void)
397 tcsetattr(0, TCSANOW, (void *) &initial_settings);
398 #if ENABLE_FEATURE_CLEAN_UP
400 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
403 #endif /* FEATURE_CLEAN_UP */
406 static void sig_catcher(int sig ATTRIBUTE_UNUSED)
411 #endif /* FEATURE_USE_TERMIOS */
414 int top_main(int argc, char **argv);
415 int top_main(int argc, char **argv)
417 int count, lines, col;
418 unsigned interval = 5; /* default update rate is 5 seconds */
419 unsigned iterations = UINT_MAX; /* 2^32 iterations by default :) */
420 char *sinterval, *siterations;
421 #if ENABLE_FEATURE_USE_TERMIOS
422 struct termios new_settings;
426 #endif /* FEATURE_USE_TERMIOS */
428 /* do normal option parsing */
430 opt_complementary = "-";
431 getopt32(argc, argv, "d:n:b", &sinterval, &siterations);
432 if (option_mask32 & 0x1) interval = xatou(sinterval); // -d
433 if (option_mask32 & 0x2) iterations = xatou(siterations); // -n
434 //if (option_mask32 & 0x4) // -b
436 /* change to /proc */
438 #if ENABLE_FEATURE_USE_TERMIOS
439 tcgetattr(0, (void *) &initial_settings);
440 memcpy(&new_settings, &initial_settings, sizeof(struct termios));
441 /* unbuffered input, turn off echo */
442 new_settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHONL);
444 signal(SIGTERM, sig_catcher);
445 signal(SIGINT, sig_catcher);
446 tcsetattr(0, TCSANOW, (void *) &new_settings);
448 #endif /* FEATURE_USE_TERMIOS */
450 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
451 sort_function[0] = pcpu_sort;
452 sort_function[1] = mem_sort;
453 sort_function[2] = time_sort;
455 sort_function = mem_sort;
456 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
459 procps_status_t *p = NULL;
461 /* Default to 25 lines - 5 lines for status */
464 #if ENABLE_FEATURE_USE_TERMIOS
465 get_terminal_width_height(0, &col, &lines);
466 if (lines < 5 || col < MIN_WIDTH) {
471 #endif /* FEATURE_USE_TERMIOS */
473 /* read process IDs & status for all the processes */
474 while ((p = procps_scan(p, 0
486 top = xrealloc(top, (++ntop)*sizeof(top_status_t));
488 top[n].ppid = p->ppid;
490 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
491 top[n].ticks = p->stime + p->utime;
494 strcpy(top[n].state, p->state);
495 strcpy(top[n].comm, p->comm);
498 bb_error_msg_and_die("can't find process info in /proc");
500 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
501 if (!prev_hist_count) {
508 qsort(top, ntop, sizeof(top_status_t), (void*)mult_lvl_cmp);
510 qsort(top, ntop, sizeof(top_status_t), (void*)sort_function);
511 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
513 if (OPT_BATCH_MODE || count > ntop) {
516 /* show status for each of the processes */
517 display_status(count, col);
518 #if ENABLE_FEATURE_USE_TERMIOS
519 tv.tv_sec = interval;
523 select(1, &readfds, NULL, NULL, &tv);
524 if (FD_ISSET(0, &readfds)) {
525 if (read(0, &c, 1) <= 0) { /* signal */
528 if (c == 'q' || c == initial_settings.c_cc[VINTR])
531 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
532 sort_function[0] = mem_sort;
533 sort_function[1] = pcpu_sort;
534 sort_function[2] = time_sort;
536 sort_function = mem_sort;
539 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
541 sort_function[0] = pcpu_sort;
542 sort_function[1] = mem_sort;
543 sort_function[2] = time_sort;
546 sort_function[0] = time_sort;
547 sort_function[1] = mem_sort;
548 sort_function[2] = pcpu_sort;
552 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
553 sort_function[0] = pid_sort;
555 sort_function = pid_sort;
563 #endif /* FEATURE_USE_TERMIOS */
566 if (ENABLE_FEATURE_CLEAN_UP)