top.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. /*
  2. * A tiny 'top' utility.
  3. *
  4. * This is written specifically for the linux /proc/<PID>/stat(m)
  5. * files format.
  6. * This reads the PIDs of all processes and their status and shows
  7. * the status of processes (first ones that fit to screen) at given
  8. * intervals.
  9. *
  10. * NOTES:
  11. * - At startup this changes to /proc, all the reads are then
  12. * relative to that.
  13. *
  14. * (C) Eero Tamminen <oak at welho dot com>
  15. *
  16. * Rewritten by Vladimir Oleynik (C) 2002 <dzo@simtreas.ru>
  17. */
  18. /* Original code Copyrights */
  19. /*
  20. * Copyright (c) 1992 Branko Lankester
  21. * Copyright (c) 1992 Roger Binns
  22. * Copyright (C) 1994-1996 Charles L. Blake.
  23. * Copyright (C) 1992-1998 Michael K. Johnson
  24. * May be distributed under the conditions of the
  25. * GNU Library General Public License
  26. */
  27. #include <sys/types.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <unistd.h>
  31. #include <string.h>
  32. #include <sys/ioctl.h>
  33. #include "busybox.h"
  34. //#define CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE /* + 2k */
  35. #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  36. #include <time.h>
  37. #include <sys/time.h>
  38. #include <fcntl.h>
  39. #include <netinet/in.h> /* htons */
  40. #endif
  41. typedef int (*cmp_t)(procps_status_t *P, procps_status_t *Q);
  42. static procps_status_t *top; /* Hehe */
  43. static int ntop;
  44. #ifdef CONFIG_FEATURE_USE_TERMIOS
  45. static int pid_sort (procps_status_t *P, procps_status_t *Q)
  46. {
  47. return (Q->pid - P->pid);
  48. }
  49. #endif
  50. static int mem_sort (procps_status_t *P, procps_status_t *Q)
  51. {
  52. return (int)(Q->rss - P->rss);
  53. }
  54. #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  55. #define sort_depth 3
  56. static cmp_t sort_function[sort_depth];
  57. static int pcpu_sort (procps_status_t *P, procps_status_t *Q)
  58. {
  59. return (Q->pcpu - P->pcpu);
  60. }
  61. static int time_sort (procps_status_t *P, procps_status_t *Q)
  62. {
  63. return (int)((Q->stime + Q->utime) - (P->stime + P->utime));
  64. }
  65. static int mult_lvl_cmp(void* a, void* b) {
  66. int i, cmp_val;
  67. for(i = 0; i < sort_depth; i++) {
  68. cmp_val = (*sort_function[i])(a, b);
  69. if (cmp_val != 0)
  70. return cmp_val;
  71. }
  72. return 0;
  73. }
  74. /* This structure stores some critical information from one frame to
  75. the next. mostly used for sorting. Added cumulative and resident fields. */
  76. struct save_hist {
  77. int ticks;
  78. int pid;
  79. int utime;
  80. int stime;
  81. };
  82. /*
  83. * Calculates percent cpu usage for each task.
  84. */
  85. static struct save_hist *save_history;
  86. static unsigned long Hertz;
  87. /***********************************************************************
  88. * Some values in /proc are expressed in units of 1/HZ seconds, where HZ
  89. * is the kernel clock tick rate. One of these units is called a jiffy.
  90. * The HZ value used in the kernel may vary according to hacker desire.
  91. * According to Linus Torvalds, this is not true. He considers the values
  92. * in /proc as being in architecture-dependent units that have no relation
  93. * to the kernel clock tick rate. Examination of the kernel source code
  94. * reveals that opinion as wishful thinking.
  95. *
  96. * In any case, we need the HZ constant as used in /proc. (the real HZ value
  97. * may differ, but we don't care) There are several ways we could get HZ:
  98. *
  99. * 1. Include the kernel header file. If it changes, recompile this library.
  100. * 2. Use the sysconf() function. When HZ changes, recompile the C library!
  101. * 3. Ask the kernel. This is obviously correct...
  102. *
  103. * Linus Torvalds won't let us ask the kernel, because he thinks we should
  104. * not know the HZ value. Oh well, we don't have to listen to him.
  105. * Someone smuggled out the HZ value. :-)
  106. *
  107. * This code should work fine, even if Linus fixes the kernel to match his
  108. * stated behavior. The code only fails in case of a partial conversion.
  109. *
  110. */
  111. #define file_to_buf_bufsize 80
  112. static inline int file_to_buf(char *buf, const char *filename, int fd)
  113. {
  114. int sz;
  115. if (fd == -1) {
  116. fd = open(filename, O_RDONLY);
  117. if(fd == -1)
  118. bb_perror_msg_and_die("is /proc mounted?");
  119. } else {
  120. lseek(fd, 0L, SEEK_SET);
  121. }
  122. sz = read(fd, buf, file_to_buf_bufsize - 1);
  123. if (sz < 0) {
  124. bb_perror_msg_and_die("%s", filename);
  125. }
  126. buf[sz] = '\0';
  127. return fd;
  128. }
  129. static void init_Hertz_value(void)
  130. {
  131. unsigned long user_j, nice_j, sys_j, other_j; /* jiffies (clock ticks) */
  132. double up_1, up_2, seconds;
  133. unsigned long jiffies, h;
  134. char buf[80];
  135. int uptime_fd = -1;
  136. int stat_fd = -1;
  137. long smp_num_cpus = sysconf(_SC_NPROCESSORS_CONF);
  138. if(smp_num_cpus<1) smp_num_cpus=1;
  139. do {
  140. uptime_fd = file_to_buf(buf, "uptime", uptime_fd);
  141. up_1 = strtod(buf, 0);
  142. stat_fd = file_to_buf(buf, "stat", stat_fd);
  143. sscanf(buf, "cpu %lu %lu %lu %lu", &user_j, &nice_j, &sys_j, &other_j);
  144. uptime_fd = file_to_buf(buf, "uptime", uptime_fd);
  145. up_2 = strtod(buf, 0);
  146. } while((long)( (up_2-up_1)*1000.0/up_1 )); /* want under 0.1% error */
  147. close(uptime_fd);
  148. close(stat_fd);
  149. jiffies = user_j + nice_j + sys_j + other_j;
  150. seconds = (up_1 + up_2) / 2;
  151. h = (unsigned long)( (double)jiffies/seconds/smp_num_cpus );
  152. /* actual values used by 2.4 kernels: 32 64 100 128 1000 1024 1200 */
  153. switch(h) {
  154. case 30 ... 34 : Hertz = 32; break; /* ia64 emulator */
  155. case 48 ... 52 : Hertz = 50; break;
  156. case 58 ... 62 : Hertz = 60; break;
  157. case 63 ... 65 : Hertz = 64; break; /* StrongARM /Shark */
  158. case 95 ... 105 : Hertz = 100; break; /* normal Linux */
  159. case 124 ... 132 : Hertz = 128; break; /* MIPS, ARM */
  160. case 195 ... 204 : Hertz = 200; break; /* normal << 1 */
  161. case 253 ... 260 : Hertz = 256; break;
  162. case 295 ... 304 : Hertz = 300; break; /* 3 cpus */
  163. case 393 ... 408 : Hertz = 400; break; /* normal << 2 */
  164. case 495 ... 504 : Hertz = 500; break; /* 5 cpus */
  165. case 595 ... 604 : Hertz = 600; break; /* 6 cpus */
  166. case 695 ... 704 : Hertz = 700; break; /* 7 cpus */
  167. case 790 ... 808 : Hertz = 800; break; /* normal << 3 */
  168. case 895 ... 904 : Hertz = 900; break; /* 9 cpus */
  169. case 990 ... 1010 : Hertz = 1000; break; /* ARM */
  170. case 1015 ... 1035 : Hertz = 1024; break; /* Alpha, ia64 */
  171. case 1095 ... 1104 : Hertz = 1100; break; /* 11 cpus */
  172. case 1180 ... 1220 : Hertz = 1200; break; /* Alpha */
  173. default:
  174. /* If 32-bit or big-endian (not Alpha or ia64), assume HZ is 100. */
  175. Hertz = (sizeof(long)==sizeof(int) || htons(999)==999) ? 100UL : 1024UL;
  176. }
  177. }
  178. static void do_stats(void)
  179. {
  180. struct timeval t;
  181. static struct timeval oldtime;
  182. struct timezone timez;
  183. float elapsed_time;
  184. procps_status_t *cur;
  185. int total_time, i, n;
  186. static int prev_count;
  187. int systime, usrtime, pid;
  188. struct save_hist *New_save_hist;
  189. /*
  190. * Finds the current time (in microseconds) and calculates the time
  191. * elapsed since the last update.
  192. */
  193. gettimeofday(&t, &timez);
  194. elapsed_time = (t.tv_sec - oldtime.tv_sec)
  195. + (float) (t.tv_usec - oldtime.tv_usec) / 1000000.0;
  196. oldtime.tv_sec = t.tv_sec;
  197. oldtime.tv_usec = t.tv_usec;
  198. New_save_hist = alloca(sizeof(struct save_hist)*ntop);
  199. /*
  200. * Make a pass through the data to get stats.
  201. */
  202. for(n = 0; n < ntop; n++) {
  203. cur = top + n;
  204. /*
  205. * Calculate time in cur process. Time is sum of user time
  206. * (usrtime) plus system time (systime).
  207. */
  208. systime = cur->stime;
  209. usrtime = cur->utime;
  210. pid = cur->pid;
  211. total_time = systime + usrtime;
  212. New_save_hist[n].ticks = total_time;
  213. New_save_hist[n].pid = pid;
  214. New_save_hist[n].stime = systime;
  215. New_save_hist[n].utime = usrtime;
  216. /* find matching entry from previous pass */
  217. for (i = 0; i < prev_count; i++) {
  218. if (save_history[i].pid == pid) {
  219. total_time -= save_history[i].ticks;
  220. systime -= save_history[i].stime;
  221. usrtime -= save_history[i].utime;
  222. break;
  223. }
  224. }
  225. /*
  226. * Calculate percent cpu time for cur task.
  227. */
  228. i = (total_time * 10 * 100/Hertz) / elapsed_time;
  229. if (i > 999)
  230. i = 999;
  231. cur->pcpu = i;
  232. }
  233. /*
  234. * Save cur frame's information.
  235. */
  236. free(save_history);
  237. save_history = memcpy(xmalloc(sizeof(struct save_hist)*n), New_save_hist,
  238. sizeof(struct save_hist)*n);
  239. prev_count = n;
  240. qsort(top, n, sizeof(procps_status_t), (void*)mult_lvl_cmp);
  241. }
  242. #else
  243. static cmp_t sort_function;
  244. #endif /* CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE */
  245. /* display generic info (meminfo / loadavg) */
  246. static unsigned long display_generic(void)
  247. {
  248. FILE *fp;
  249. char buf[80];
  250. float avg1, avg2, avg3;
  251. unsigned long total, used, mfree, shared, buffers, cached;
  252. unsigned int needs_conversion = 1;
  253. /* read memory info */
  254. fp = bb_xfopen("meminfo", "r");
  255. /*
  256. * Old kernels (such as 2.4.x) had a nice summary of memory info that
  257. * we could parse, however this is gone entirely in 2.6. Try parsing
  258. * the old way first, and if that fails, parse each field manually.
  259. *
  260. * First, we read in the first line. Old kernels will have bogus
  261. * strings we don't care about, whereas new kernels will start right
  262. * out with MemTotal:
  263. * -- PFM.
  264. */
  265. if (fscanf(fp, "MemTotal: %lu %s\n", &total, buf) != 2) {
  266. 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. } else {
  270. /*
  271. * Revert to manual parsing, which incidentally already has the
  272. * sizes in kilobytes. This should be safe for both 2.4 and
  273. * 2.6.
  274. */
  275. needs_conversion = 0;
  276. fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
  277. /*
  278. * MemShared: is no longer present in 2.6. Report this as 0,
  279. * to maintain consistent behavior with normal procps.
  280. */
  281. if (fscanf(fp, "MemShared: %lu %s\n", &shared, buf) != 2)
  282. shared = 0;
  283. fscanf(fp, "Buffers: %lu %s\n", &buffers, buf);
  284. fscanf(fp, "Cached: %lu %s\n", &cached, buf);
  285. used = total - mfree;
  286. }
  287. fclose(fp);
  288. /* read load average */
  289. fp = bb_xfopen("loadavg", "r");
  290. if (fscanf(fp, "%f %f %f", &avg1, &avg2, &avg3) != 3) {
  291. bb_error_msg_and_die("failed to read 'loadavg'");
  292. }
  293. fclose(fp);
  294. if (needs_conversion) {
  295. /* convert to kilobytes */
  296. used /= 1024;
  297. mfree /= 1024;
  298. shared /= 1024;
  299. buffers /= 1024;
  300. cached /= 1024;
  301. total /= 1024;
  302. }
  303. /* output memory info and load average */
  304. /* clear screen & go to top */
  305. printf("\e[H\e[J" "Mem: "
  306. "%ldK used, %ldK free, %ldK shrd, %ldK buff, %ldK cached\n",
  307. used, mfree, shared, buffers, cached);
  308. printf("Load average: %.2f, %.2f, %.2f "
  309. "(State: S=sleeping R=running, W=waiting)\n",
  310. avg1, avg2, avg3);
  311. return total;
  312. }
  313. /* display process statuses */
  314. static void display_status(int count, int col)
  315. {
  316. procps_status_t *s = top;
  317. char rss_str_buf[8];
  318. unsigned long total_memory = display_generic();
  319. #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  320. /* what info of the processes is shown */
  321. printf("\n\e[7m PID USER STATUS RSS PPID %%CPU %%MEM COMMAND\e[0m\n");
  322. #else
  323. printf("\n\e[7m PID USER STATUS RSS PPID %%MEM COMMAND\e[0m\n");
  324. #endif
  325. while (count--) {
  326. char *namecmd = s->short_cmd;
  327. int pmem;
  328. pmem = 1000.0 * s->rss / total_memory;
  329. if (pmem > 999) pmem = 999;
  330. if(s->rss > 10*1024)
  331. sprintf(rss_str_buf, "%6ldM", s->rss/1024);
  332. else
  333. sprintf(rss_str_buf, "%7ld", s->rss);
  334. #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  335. printf("%5d %-8s %s %s %5d %2d.%d %2u.%u ",
  336. s->pid, s->user, s->state, rss_str_buf, s->ppid,
  337. s->pcpu/10, s->pcpu%10, pmem/10, pmem%10);
  338. #else
  339. printf("%5d %-8s %s %s %5d %2u.%u ",
  340. s->pid, s->user, s->state, rss_str_buf, s->ppid,
  341. pmem/10, pmem%10);
  342. #endif
  343. if((int)strlen(namecmd) > col)
  344. namecmd[col] = 0;
  345. printf("%s", namecmd);
  346. if(count)
  347. putchar('\n');
  348. else
  349. fflush(stdout);
  350. s++;
  351. }
  352. }
  353. static void clearmems(void)
  354. {
  355. free(top);
  356. top = 0;
  357. ntop = 0;
  358. }
  359. #ifdef CONFIG_FEATURE_USE_TERMIOS
  360. #include <termios.h>
  361. #include <sys/time.h>
  362. #include <signal.h>
  363. static struct termios initial_settings;
  364. static void reset_term(void)
  365. {
  366. tcsetattr(0, TCSANOW, (void *) &initial_settings);
  367. #ifdef CONFIG_FEATURE_CLEAN_UP
  368. clearmems();
  369. #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  370. free(save_history);
  371. #endif
  372. #endif /* CONFIG_FEATURE_CLEAN_UP */
  373. }
  374. static void sig_catcher(int sig ATTRIBUTE_UNUSED)
  375. {
  376. reset_term();
  377. }
  378. #endif /* CONFIG_FEATURE_USE_TERMIOS */
  379. int top_main(int argc, char **argv)
  380. {
  381. int opt, interval, lines, col;
  382. char *sinterval;
  383. #ifdef CONFIG_FEATURE_USE_TERMIOS
  384. struct termios new_settings;
  385. struct timeval tv;
  386. fd_set readfds;
  387. unsigned char c;
  388. struct sigaction sa;
  389. #endif /* CONFIG_FEATURE_USE_TERMIOS */
  390. /* do normal option parsing */
  391. opt = bb_getopt_ulflags(argc, argv, "d:", &sinterval);
  392. if((opt & 1)) {
  393. interval = atoi(sinterval);
  394. } else {
  395. /* Default update rate is 5 seconds */
  396. interval = 5;
  397. }
  398. /* Default to 25 lines - 5 lines for status */
  399. lines = 25 - 5;
  400. /* Default CMD format size */
  401. #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  402. col = 35 - 6;
  403. #else
  404. col = 35;
  405. #endif
  406. /* change to /proc */
  407. if (chdir("/proc") < 0) {
  408. bb_perror_msg_and_die("chdir('/proc')");
  409. }
  410. #ifdef CONFIG_FEATURE_USE_TERMIOS
  411. tcgetattr(0, (void *) &initial_settings);
  412. memcpy(&new_settings, &initial_settings, sizeof(struct termios));
  413. new_settings.c_lflag &= ~(ISIG | ICANON); /* unbuffered input */
  414. /* Turn off echoing */
  415. new_settings.c_lflag &= ~(ECHO | ECHONL);
  416. signal (SIGTERM, sig_catcher);
  417. sigaction (SIGTERM, (struct sigaction *) 0, &sa);
  418. sa.sa_flags |= SA_RESTART;
  419. sa.sa_flags &= ~SA_INTERRUPT;
  420. sigaction (SIGTERM, &sa, (struct sigaction *) 0);
  421. sigaction (SIGINT, &sa, (struct sigaction *) 0);
  422. tcsetattr(0, TCSANOW, (void *) &new_settings);
  423. atexit(reset_term);
  424. get_terminal_width_height(0, &col, &lines);
  425. if (lines > 4) {
  426. lines -= 4;
  427. #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  428. col = col - 80 + 35 - 6;
  429. #else
  430. col = col - 80 + 35;
  431. #endif
  432. }
  433. #endif /* CONFIG_FEATURE_USE_TERMIOS */
  434. #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  435. sort_function[0] = pcpu_sort;
  436. sort_function[1] = mem_sort;
  437. sort_function[2] = time_sort;
  438. #else
  439. sort_function = mem_sort;
  440. #endif /* CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE */
  441. while (1) {
  442. /* read process IDs & status for all the processes */
  443. procps_status_t * p;
  444. while ((p = procps_scan(0)) != 0) {
  445. int n = ntop;
  446. top = xrealloc(top, (++ntop)*sizeof(procps_status_t));
  447. memcpy(top + n, p, sizeof(procps_status_t));
  448. }
  449. if (ntop == 0) {
  450. bb_error_msg_and_die("Can't find process info in /proc");
  451. }
  452. #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  453. if(!Hertz) {
  454. init_Hertz_value();
  455. do_stats();
  456. sleep(1);
  457. clearmems();
  458. continue;
  459. }
  460. do_stats();
  461. #else
  462. qsort(top, ntop, sizeof(procps_status_t), (void*)sort_function);
  463. #endif /* CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE */
  464. opt = lines;
  465. if (opt > ntop) {
  466. opt = ntop;
  467. }
  468. /* show status for each of the processes */
  469. display_status(opt, col);
  470. #ifdef CONFIG_FEATURE_USE_TERMIOS
  471. tv.tv_sec = interval;
  472. tv.tv_usec = 0;
  473. FD_ZERO (&readfds);
  474. FD_SET (0, &readfds);
  475. select (1, &readfds, NULL, NULL, &tv);
  476. if (FD_ISSET (0, &readfds)) {
  477. if (read (0, &c, 1) <= 0) { /* signal */
  478. return EXIT_FAILURE;
  479. }
  480. if(c == 'q' || c == initial_settings.c_cc[VINTR])
  481. break;
  482. if(c == 'M') {
  483. #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  484. sort_function[0] = mem_sort;
  485. sort_function[1] = pcpu_sort;
  486. sort_function[2] = time_sort;
  487. #else
  488. sort_function = mem_sort;
  489. #endif
  490. }
  491. #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  492. if(c == 'P') {
  493. sort_function[0] = pcpu_sort;
  494. sort_function[1] = mem_sort;
  495. sort_function[2] = time_sort;
  496. }
  497. if(c == 'T') {
  498. sort_function[0] = time_sort;
  499. sort_function[1] = mem_sort;
  500. sort_function[2] = pcpu_sort;
  501. }
  502. #endif
  503. if(c == 'N') {
  504. #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  505. sort_function[0] = pid_sort;
  506. #else
  507. sort_function = pid_sort;
  508. #endif
  509. }
  510. }
  511. #else
  512. sleep(interval);
  513. #endif /* CONFIG_FEATURE_USE_TERMIOS */
  514. clearmems();
  515. }
  516. if(ENABLE_FEATURE_CLEAN_UP)
  517. clearmems();
  518. putchar('\n');
  519. return EXIT_SUCCESS;
  520. }