top.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. /* get page info */
  34. #include <asm/page.h>
  35. #include "busybox.h"
  36. //#define FEATURE_CPU_USAGE_PERCENTAGE /* + 2k */
  37. #ifdef FEATURE_CPU_USAGE_PERCENTAGE
  38. #include <time.h>
  39. #include <sys/time.h>
  40. #include <fcntl.h>
  41. #include <netinet/in.h> /* htons */
  42. #endif
  43. typedef int (*cmp_t)(procps_status_t *P, procps_status_t *Q);
  44. static procps_status_t *top; /* Hehe */
  45. static int ntop;
  46. static int pid_sort (procps_status_t *P, procps_status_t *Q)
  47. {
  48. return (Q->pid - P->pid);
  49. }
  50. static int mem_sort (procps_status_t *P, procps_status_t *Q)
  51. {
  52. return (int)(Q->rss - P->rss);
  53. }
  54. #ifdef FEATURE_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(filename, fd) do{ \
  112. if (fd == -1 && (fd = open(filename, O_RDONLY)) == -1) { \
  113. bb_perror_msg_and_die("/proc not be mounted?"); \
  114. } \
  115. lseek(fd, 0L, SEEK_SET); \
  116. if ((local_n = read(fd, buf, sizeof buf - 1)) < 0) { \
  117. bb_perror_msg_and_die("%s", filename); \
  118. } \
  119. buf[local_n] = '\0'; \
  120. }while(0)
  121. #define FILE_TO_BUF2(filename, fd) do{ \
  122. lseek(fd, 0L, SEEK_SET); \
  123. if ((local_n = read(fd, buf, sizeof buf - 1)) < 0) { \
  124. bb_perror_msg_and_die("%s", filename); \
  125. } \
  126. buf[local_n] = '\0'; \
  127. }while(0)
  128. static void init_Hertz_value(void) {
  129. unsigned long user_j, nice_j, sys_j, other_j; /* jiffies (clock ticks) */
  130. double up_1, up_2, seconds;
  131. unsigned long jiffies, h;
  132. char buf[80];
  133. int uptime_fd = -1;
  134. int stat_fd = -1;
  135. long smp_num_cpus = sysconf(_SC_NPROCESSORS_CONF);
  136. if(smp_num_cpus<1) smp_num_cpus=1;
  137. do {
  138. int local_n;
  139. FILE_TO_BUF("uptime", uptime_fd);
  140. up_1 = strtod(buf, 0);
  141. FILE_TO_BUF("stat", stat_fd);
  142. sscanf(buf, "cpu %lu %lu %lu %lu", &user_j, &nice_j, &sys_j, &other_j);
  143. FILE_TO_BUF2("uptime", uptime_fd);
  144. up_2 = strtod(buf, 0);
  145. } while((long)( (up_2-up_1)*1000.0/up_1 )); /* want under 0.1% error */
  146. close(uptime_fd);
  147. close(stat_fd);
  148. jiffies = user_j + nice_j + sys_j + other_j;
  149. seconds = (up_1 + up_2) / 2;
  150. h = (unsigned long)( (double)jiffies/seconds/smp_num_cpus );
  151. /* actual values used by 2.4 kernels: 32 64 100 128 1000 1024 1200 */
  152. switch(h){
  153. case 30 ... 34 : Hertz = 32; break; /* ia64 emulator */
  154. case 48 ... 52 : Hertz = 50; break;
  155. case 58 ... 62 : Hertz = 60; break;
  156. case 63 ... 65 : Hertz = 64; break; /* StrongARM /Shark */
  157. case 95 ... 105 : Hertz = 100; break; /* normal Linux */
  158. case 124 ... 132 : Hertz = 128; break; /* MIPS, ARM */
  159. case 195 ... 204 : Hertz = 200; break; /* normal << 1 */
  160. case 253 ... 260 : Hertz = 256; break;
  161. case 295 ... 304 : Hertz = 300; break; /* 3 cpus */
  162. case 393 ... 408 : Hertz = 400; break; /* normal << 2 */
  163. case 495 ... 504 : Hertz = 500; break; /* 5 cpus */
  164. case 595 ... 604 : Hertz = 600; break; /* 6 cpus */
  165. case 695 ... 704 : Hertz = 700; break; /* 7 cpus */
  166. case 790 ... 808 : Hertz = 800; break; /* normal << 3 */
  167. case 895 ... 904 : Hertz = 900; break; /* 9 cpus */
  168. case 990 ... 1010 : Hertz = 1000; break; /* ARM */
  169. case 1015 ... 1035 : Hertz = 1024; break; /* Alpha, ia64 */
  170. case 1095 ... 1104 : Hertz = 1100; break; /* 11 cpus */
  171. case 1180 ... 1220 : Hertz = 1200; break; /* Alpha */
  172. default:
  173. /* If 32-bit or big-endian (not Alpha or ia64), assume HZ is 100. */
  174. Hertz = (sizeof(long)==sizeof(int) || htons(999)==999) ? 100UL : 1024UL;
  175. }
  176. }
  177. static void do_stats(void)
  178. {
  179. struct timeval t;
  180. static struct timeval oldtime;
  181. struct timezone timez;
  182. float elapsed_time;
  183. procps_status_t *cur;
  184. int total_time, i, n;
  185. static int prev_count;
  186. int systime, usrtime, pid;
  187. struct save_hist *New_save_hist;
  188. /*
  189. * Finds the current time (in microseconds) and calculates the time
  190. * elapsed since the last update.
  191. */
  192. gettimeofday(&t, &timez);
  193. elapsed_time = (t.tv_sec - oldtime.tv_sec)
  194. + (float) (t.tv_usec - oldtime.tv_usec) / 1000000.0;
  195. oldtime.tv_sec = t.tv_sec;
  196. oldtime.tv_usec = t.tv_usec;
  197. New_save_hist = alloca(sizeof(struct save_hist)*ntop);
  198. /*
  199. * Make a pass through the data to get stats.
  200. */
  201. for(n = 0; n < ntop; n++) {
  202. cur = top + n;
  203. /*
  204. * Calculate time in cur process. Time is sum of user time
  205. * (usrtime) plus system time (systime).
  206. */
  207. systime = cur->stime;
  208. usrtime = cur->utime;
  209. pid = cur->pid;
  210. total_time = systime + usrtime;
  211. New_save_hist[n].ticks = total_time;
  212. New_save_hist[n].pid = pid;
  213. New_save_hist[n].stime = systime;
  214. New_save_hist[n].utime = usrtime;
  215. /* find matching entry from previous pass */
  216. for (i = 0; i < prev_count; i++) {
  217. if (save_history[i].pid == pid) {
  218. total_time -= save_history[i].ticks;
  219. systime -= save_history[i].stime;
  220. usrtime -= save_history[i].utime;
  221. break;
  222. }
  223. }
  224. /*
  225. * Calculate percent cpu time for cur task.
  226. */
  227. i = (total_time * 10 * 100/Hertz) / elapsed_time;
  228. if (i > 999)
  229. i = 999;
  230. cur->pcpu = i;
  231. }
  232. /*
  233. * Save cur frame's information.
  234. */
  235. free(save_history);
  236. save_history = memcpy(xmalloc(sizeof(struct save_hist)*n), New_save_hist,
  237. sizeof(struct save_hist)*n);
  238. prev_count = n;
  239. qsort(top, n, sizeof(procps_status_t), (void*)mult_lvl_cmp);
  240. }
  241. #else
  242. static cmp_t sort_function;
  243. #endif /* FEATURE_CPU_USAGE_PERCENTAGE */
  244. /* display generic info (meminfo / loadavg) */
  245. static unsigned long display_generic(void)
  246. {
  247. FILE *fp;
  248. char buf[80];
  249. float avg1, avg2, avg3;
  250. unsigned long total, used, mfree, shared, buffers, cached;
  251. unsigned int needs_conversion = 1;
  252. /* read memory info */
  253. fp = bb_xfopen("meminfo", "r");
  254. /*
  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.
  258. *
  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
  261. * out with MemTotal:
  262. * -- PFM.
  263. */
  264. if (fscanf(fp, "MemTotal: %lu %s\n", &total, buf) != 2) {
  265. fgets(buf, sizeof(buf), fp); /* skip first line */
  266. fscanf(fp, "Mem: %lu %lu %lu %lu %lu %lu",
  267. &total, &used, &mfree, &shared, &buffers, &cached);
  268. } else {
  269. /*
  270. * Revert to manual parsing, which incidentally already has the
  271. * sizes in kilobytes. This should be safe for both 2.4 and
  272. * 2.6.
  273. */
  274. needs_conversion = 0;
  275. fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
  276. /*
  277. * MemShared: is no longer present in 2.6. Report this as 0,
  278. * to maintain consistent behavior with normal procps.
  279. */
  280. if (fscanf(fp, "MemShared: %lu %s\n", &shared, buf) != 2)
  281. shared = 0;
  282. fscanf(fp, "Buffers: %lu %s\n", &buffers, buf);
  283. fscanf(fp, "Cached: %lu %s\n", &cached, buf);
  284. used = total - mfree;
  285. }
  286. fclose(fp);
  287. /* read load average */
  288. fp = bb_xfopen("loadavg", "r");
  289. if (fscanf(fp, "%f %f %f", &avg1, &avg2, &avg3) != 3) {
  290. bb_error_msg_and_die("failed to read '%s'", "loadavg");
  291. }
  292. fclose(fp);
  293. if (needs_conversion) {
  294. /* convert to kilobytes */
  295. used /= 1024;
  296. mfree /= 1024;
  297. shared /= 1024;
  298. buffers /= 1024;
  299. cached /= 1024;
  300. total /= 1024;
  301. }
  302. /* output memory info and load average */
  303. /* clear screen & go to top */
  304. printf("\e[H\e[J" "Mem: "
  305. "%ldK used, %ldK free, %ldK shrd, %ldK buff, %ldK cached\n",
  306. used, mfree, shared, buffers, cached);
  307. printf("Load average: %.2f, %.2f, %.2f "
  308. "(State: S=sleeping R=running, W=waiting)\n",
  309. avg1, avg2, avg3);
  310. return total;
  311. }
  312. /* display process statuses */
  313. static void display_status(int count, int col)
  314. {
  315. procps_status_t *s = top;
  316. char rss_str_buf[8];
  317. unsigned long total_memory = display_generic();
  318. #ifdef FEATURE_CPU_USAGE_PERCENTAGE
  319. /* what info of the processes is shown */
  320. printf("\n\e[7m PID USER STATUS RSS PPID %%CPU %%MEM COMMAND\e[0m\n");
  321. #else
  322. printf("\n\e[7m PID USER STATUS RSS PPID %%MEM COMMAND\e[0m\n");
  323. #endif
  324. while (count--) {
  325. char *namecmd = s->short_cmd;
  326. int pmem;
  327. pmem = 1000.0 * s->rss / total_memory;
  328. if (pmem > 999) pmem = 999;
  329. if(s->rss > 10*1024)
  330. sprintf(rss_str_buf, "%6ldM", s->rss/1024);
  331. else
  332. sprintf(rss_str_buf, "%7ld", s->rss);
  333. #ifdef FEATURE_CPU_USAGE_PERCENTAGE
  334. printf("%5d %-8s %s %s %5d %2d.%d %2u.%u ",
  335. s->pid, s->user, s->state, rss_str_buf, s->ppid,
  336. s->pcpu/10, s->pcpu%10, pmem/10, pmem%10);
  337. #else
  338. printf("%5d %-8s %s %s %5d %2u.%u ",
  339. s->pid, s->user, s->state, rss_str_buf, s->ppid,
  340. pmem/10, pmem%10);
  341. #endif
  342. if(strlen(namecmd) > col)
  343. namecmd[col] = 0;
  344. printf("%s\n", namecmd);
  345. s++;
  346. }
  347. }
  348. static void clearmems(void)
  349. {
  350. free(top);
  351. top = 0;
  352. ntop = 0;
  353. }
  354. #if defined CONFIG_FEATURE_USE_TERMIOS
  355. #include <termios.h>
  356. #include <sys/time.h>
  357. #include <signal.h>
  358. static struct termios initial_settings;
  359. static void reset_term(void)
  360. {
  361. tcsetattr(0, TCSANOW, (void *) &initial_settings);
  362. #ifdef CONFIG_FEATURE_CLEAN_UP
  363. clearmems();
  364. #ifdef FEATURE_CPU_USAGE_PERCENTAGE
  365. free(save_history);
  366. #endif
  367. #endif /* CONFIG_FEATURE_CLEAN_UP */
  368. }
  369. static void sig_catcher (int sig)
  370. {
  371. reset_term();
  372. }
  373. #endif /* CONFIG_FEATURE_USE_TERMIOS */
  374. int top_main(int argc, char **argv)
  375. {
  376. int opt, interval, lines, col;
  377. #if defined CONFIG_FEATURE_USE_TERMIOS
  378. struct termios new_settings;
  379. struct timeval tv;
  380. fd_set readfds;
  381. unsigned char c;
  382. struct sigaction sa;
  383. #endif /* CONFIG_FEATURE_USE_TERMIOS */
  384. /* Default update rate is 5 seconds */
  385. interval = 5;
  386. /* do normal option parsing */
  387. while ((opt = getopt(argc, argv, "d:")) > 0) {
  388. switch (opt) {
  389. case 'd':
  390. interval = atoi(optarg);
  391. break;
  392. default:
  393. bb_show_usage();
  394. }
  395. }
  396. /* Default to 25 lines - 5 lines for status */
  397. lines = 25 - 5;
  398. /* Default CMD format size */
  399. #ifdef FEATURE_CPU_USAGE_PERCENTAGE
  400. col = 35 - 6;
  401. #else
  402. col = 35;
  403. #endif
  404. /* change to /proc */
  405. if (chdir("/proc") < 0) {
  406. bb_perror_msg_and_die("chdir('/proc')");
  407. }
  408. #if defined CONFIG_FEATURE_USE_TERMIOS
  409. tcgetattr(0, (void *) &initial_settings);
  410. memcpy(&new_settings, &initial_settings, sizeof(struct termios));
  411. new_settings.c_lflag &= ~(ISIG | ICANON); /* unbuffered input */
  412. /* Turn off echoing */
  413. new_settings.c_lflag &= ~(ECHO | ECHONL);
  414. signal (SIGTERM, sig_catcher);
  415. sigaction (SIGTERM, (struct sigaction *) 0, &sa);
  416. sa.sa_flags |= SA_RESTART;
  417. sa.sa_flags &= ~SA_INTERRUPT;
  418. sigaction (SIGTERM, &sa, (struct sigaction *) 0);
  419. sigaction (SIGINT, &sa, (struct sigaction *) 0);
  420. tcsetattr(0, TCSANOW, (void *) &new_settings);
  421. atexit(reset_term);
  422. get_terminal_width_height(0, &col, &lines);
  423. if (lines > 4) {
  424. lines -= 5;
  425. #ifdef FEATURE_CPU_USAGE_PERCENTAGE
  426. col = col - 80 + 35 - 6;
  427. #else
  428. col = col - 80 + 35;
  429. #endif
  430. }
  431. #endif /* CONFIG_FEATURE_USE_TERMIOS */
  432. #ifdef FEATURE_CPU_USAGE_PERCENTAGE
  433. sort_function[0] = pcpu_sort;
  434. sort_function[1] = mem_sort;
  435. sort_function[2] = time_sort;
  436. #else
  437. sort_function = mem_sort;
  438. #endif
  439. while (1) {
  440. /* read process IDs & status for all the processes */
  441. procps_status_t * p;
  442. #ifdef CONFIG_SELINUX
  443. while ((p = procps_scan(0, 0, NULL) ) != 0) {
  444. #else
  445. while ((p = procps_scan(0)) != 0) {
  446. #endif
  447. int n = ntop;
  448. top = xrealloc(top, (++ntop)*sizeof(procps_status_t));
  449. memcpy(top + n, p, sizeof(procps_status_t));
  450. }
  451. if (ntop == 0) {
  452. bb_perror_msg_and_die("scandir('/proc')");
  453. }
  454. #ifdef FEATURE_CPU_USAGE_PERCENTAGE
  455. if(!Hertz) {
  456. init_Hertz_value();
  457. do_stats();
  458. sleep(1);
  459. clearmems();
  460. continue;
  461. }
  462. do_stats();
  463. #else
  464. qsort(top, ntop, sizeof(procps_status_t), (void*)sort_function);
  465. #endif
  466. opt = lines;
  467. if (opt > ntop) {
  468. opt = ntop;
  469. }
  470. /* show status for each of the processes */
  471. display_status(opt, col);
  472. #if defined CONFIG_FEATURE_USE_TERMIOS
  473. tv.tv_sec = interval;
  474. tv.tv_usec = 0;
  475. FD_ZERO (&readfds);
  476. FD_SET (0, &readfds);
  477. select (1, &readfds, NULL, NULL, &tv);
  478. if (FD_ISSET (0, &readfds)) {
  479. if (read (0, &c, 1) <= 0) { /* signal */
  480. return EXIT_FAILURE;
  481. }
  482. if(c == 'q' || c == initial_settings.c_cc[VINTR])
  483. return EXIT_SUCCESS;
  484. if(c == 'M') {
  485. #ifdef FEATURE_CPU_USAGE_PERCENTAGE
  486. sort_function[0] = mem_sort;
  487. sort_function[1] = pcpu_sort;
  488. sort_function[2] = time_sort;
  489. #else
  490. sort_function = mem_sort;
  491. #endif
  492. }
  493. #ifdef FEATURE_CPU_USAGE_PERCENTAGE
  494. if(c == 'P') {
  495. sort_function[0] = pcpu_sort;
  496. sort_function[1] = mem_sort;
  497. sort_function[2] = time_sort;
  498. }
  499. if(c == 'T') {
  500. sort_function[0] = time_sort;
  501. sort_function[1] = mem_sort;
  502. sort_function[2] = pcpu_sort;
  503. }
  504. #endif
  505. if(c == 'N') {
  506. #ifdef FEATURE_CPU_USAGE_PERCENTAGE
  507. sort_function[0] = pid_sort;
  508. #else
  509. sort_function = pid_sort;
  510. #endif
  511. }
  512. }
  513. #else
  514. sleep(interval);
  515. #endif /* CONFIG_FEATURE_USE_TERMIOS */
  516. clearmems();
  517. }
  518. return EXIT_SUCCESS;
  519. }