top.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * A tiny 'top' utility.
  4. *
  5. * This is written specifically for the linux /proc/<PID>/stat(m)
  6. * files format.
  7. * This reads the PIDs of all processes and their status and shows
  8. * the status of processes (first ones that fit to screen) at given
  9. * intervals.
  10. *
  11. * NOTES:
  12. * - At startup this changes to /proc, all the reads are then
  13. * relative to that.
  14. *
  15. * (C) Eero Tamminen <oak at welho dot com>
  16. *
  17. * Rewritten by Vladimir Oleynik (C) 2002 <dzo@simtreas.ru>
  18. */
  19. /* Original code Copyrights */
  20. /*
  21. * Copyright (c) 1992 Branko Lankester
  22. * Copyright (c) 1992 Roger Binns
  23. * Copyright (C) 1994-1996 Charles L. Blake.
  24. * Copyright (C) 1992-1998 Michael K. Johnson
  25. * May be distributed under the conditions of the
  26. * GNU Library General Public License
  27. */
  28. #include "libbb.h"
  29. typedef struct top_status_t {
  30. unsigned long vsz;
  31. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  32. unsigned long ticks;
  33. unsigned pcpu; /* delta of ticks */
  34. #endif
  35. unsigned pid, ppid;
  36. unsigned uid;
  37. char state[4];
  38. char comm[COMM_LEN];
  39. } top_status_t;
  40. typedef struct jiffy_counts_t {
  41. unsigned long long usr,nic,sys,idle,iowait,irq,softirq,steal;
  42. unsigned long long total;
  43. unsigned long long busy;
  44. } jiffy_counts_t;
  45. /* This structure stores some critical information from one frame to
  46. the next. Used for finding deltas. */
  47. typedef struct save_hist {
  48. unsigned long ticks;
  49. unsigned pid;
  50. } save_hist;
  51. typedef int (*cmp_funcp)(top_status_t *P, top_status_t *Q);
  52. enum { SORT_DEPTH = 3 };
  53. struct globals {
  54. top_status_t *top;
  55. int ntop;
  56. #if ENABLE_FEATURE_TOPMEM
  57. smallint sort_field;
  58. smallint inverted;
  59. #endif
  60. #if ENABLE_FEATURE_USE_TERMIOS
  61. struct termios initial_settings;
  62. #endif
  63. #if !ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  64. cmp_funcp sort_function[1];
  65. #else
  66. cmp_funcp sort_function[SORT_DEPTH];
  67. struct save_hist *prev_hist;
  68. int prev_hist_count;
  69. jiffy_counts_t jif, prev_jif;
  70. /* int hist_iterations; */
  71. unsigned total_pcpu;
  72. /* unsigned long total_vsz; */
  73. #endif
  74. char line_buf[80];
  75. };
  76. enum { LINE_BUF_SIZE = COMMON_BUFSIZE - offsetof(struct globals, line_buf) };
  77. #define G (*(struct globals*)&bb_common_bufsiz1)
  78. #define INIT_G() \
  79. do { \
  80. struct G_sizecheck { \
  81. char G_sizecheck[sizeof(G) > COMMON_BUFSIZE ? -1 : 1]; \
  82. }; \
  83. } while (0)
  84. #define top (G.top )
  85. #define ntop (G.ntop )
  86. #define sort_field (G.sort_field )
  87. #define inverted (G.inverted )
  88. #define initial_settings (G.initial_settings )
  89. #define sort_function (G.sort_function )
  90. #define prev_hist (G.prev_hist )
  91. #define prev_hist_count (G.prev_hist_count )
  92. #define jif (G.jif )
  93. #define prev_jif (G.prev_jif )
  94. #define total_pcpu (G.total_pcpu )
  95. #define line_buf (G.line_buf )
  96. enum {
  97. OPT_d = (1 << 0),
  98. OPT_n = (1 << 1),
  99. OPT_b = (1 << 2),
  100. OPT_EOF = (1 << 3), /* pseudo: "we saw EOF in stdin" */
  101. };
  102. #define OPT_BATCH_MODE (option_mask32 & OPT_b)
  103. #if ENABLE_FEATURE_USE_TERMIOS
  104. static int pid_sort(top_status_t *P, top_status_t *Q)
  105. {
  106. /* Buggy wrt pids with high bit set */
  107. /* (linux pids are in [1..2^15-1]) */
  108. return (Q->pid - P->pid);
  109. }
  110. #endif
  111. static int mem_sort(top_status_t *P, top_status_t *Q)
  112. {
  113. /* We want to avoid unsigned->signed and truncation errors */
  114. if (Q->vsz < P->vsz) return -1;
  115. return Q->vsz != P->vsz; /* 0 if ==, 1 if > */
  116. }
  117. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  118. static int pcpu_sort(top_status_t *P, top_status_t *Q)
  119. {
  120. /* Buggy wrt ticks with high bit set */
  121. /* Affects only processes for which ticks overflow */
  122. return (int)Q->pcpu - (int)P->pcpu;
  123. }
  124. static int time_sort(top_status_t *P, top_status_t *Q)
  125. {
  126. /* We want to avoid unsigned->signed and truncation errors */
  127. if (Q->ticks < P->ticks) return -1;
  128. return Q->ticks != P->ticks; /* 0 if ==, 1 if > */
  129. }
  130. static int mult_lvl_cmp(void* a, void* b)
  131. {
  132. int i, cmp_val;
  133. for (i = 0; i < SORT_DEPTH; i++) {
  134. cmp_val = (*sort_function[i])(a, b);
  135. if (cmp_val != 0)
  136. return cmp_val;
  137. }
  138. return 0;
  139. }
  140. static void get_jiffy_counts(void)
  141. {
  142. FILE* fp = xfopen("stat", "r");
  143. prev_jif = jif;
  144. if (fscanf(fp, "cpu %lld %lld %lld %lld %lld %lld %lld %lld",
  145. &jif.usr,&jif.nic,&jif.sys,&jif.idle,
  146. &jif.iowait,&jif.irq,&jif.softirq,&jif.steal) < 4) {
  147. bb_error_msg_and_die("can't read /proc/stat");
  148. }
  149. fclose(fp);
  150. jif.total = jif.usr + jif.nic + jif.sys + jif.idle
  151. + jif.iowait + jif.irq + jif.softirq + jif.steal;
  152. /* procps 2.x does not count iowait as busy time */
  153. jif.busy = jif.total - jif.idle - jif.iowait;
  154. }
  155. static void do_stats(void)
  156. {
  157. top_status_t *cur;
  158. pid_t pid;
  159. int i, last_i, n;
  160. struct save_hist *new_hist;
  161. get_jiffy_counts();
  162. total_pcpu = 0;
  163. /* total_vsz = 0; */
  164. new_hist = xmalloc(sizeof(struct save_hist)*ntop);
  165. /*
  166. * Make a pass through the data to get stats.
  167. */
  168. /* hist_iterations = 0; */
  169. i = 0;
  170. for (n = 0; n < ntop; n++) {
  171. cur = top + n;
  172. /*
  173. * Calculate time in cur process. Time is sum of user time
  174. * and system time
  175. */
  176. pid = cur->pid;
  177. new_hist[n].ticks = cur->ticks;
  178. new_hist[n].pid = pid;
  179. /* find matching entry from previous pass */
  180. cur->pcpu = 0;
  181. /* do not start at index 0, continue at last used one
  182. * (brought hist_iterations from ~14000 down to 172) */
  183. last_i = i;
  184. if (prev_hist_count) do {
  185. if (prev_hist[i].pid == pid) {
  186. cur->pcpu = cur->ticks - prev_hist[i].ticks;
  187. total_pcpu += cur->pcpu;
  188. break;
  189. }
  190. i = (i+1) % prev_hist_count;
  191. /* hist_iterations++; */
  192. } while (i != last_i);
  193. /* total_vsz += cur->vsz; */
  194. }
  195. /*
  196. * Save cur frame's information.
  197. */
  198. free(prev_hist);
  199. prev_hist = new_hist;
  200. prev_hist_count = ntop;
  201. }
  202. #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
  203. #if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS && ENABLE_FEATURE_TOP_DECIMALS
  204. /* formats 7 char string (8 with terminating NUL) */
  205. static char *fmt_100percent_8(char pbuf[8], unsigned value, unsigned total)
  206. {
  207. unsigned t;
  208. if (value >= total) { /* 100% ? */
  209. strcpy(pbuf, " 100% ");
  210. return pbuf;
  211. }
  212. /* else generate " [N/space]N.N% " string */
  213. value = 1000 * value / total;
  214. t = value / 100;
  215. value = value % 100;
  216. pbuf[0] = ' ';
  217. pbuf[1] = t ? t + '0' : ' ';
  218. pbuf[2] = '0' + (value / 10);
  219. pbuf[3] = '.';
  220. pbuf[4] = '0' + (value % 10);
  221. pbuf[5] = '%';
  222. pbuf[6] = ' ';
  223. pbuf[7] = '\0';
  224. return pbuf;
  225. }
  226. #endif
  227. static unsigned long display_header(int scr_width)
  228. {
  229. FILE *fp;
  230. char buf[80];
  231. char scrbuf[80];
  232. unsigned long total, used, mfree, shared, buffers, cached;
  233. #if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS
  234. unsigned total_diff;
  235. #endif
  236. /* read memory info */
  237. fp = xfopen("meminfo", "r");
  238. /*
  239. * Old kernels (such as 2.4.x) had a nice summary of memory info that
  240. * we could parse, however this is gone entirely in 2.6. Try parsing
  241. * the old way first, and if that fails, parse each field manually.
  242. *
  243. * First, we read in the first line. Old kernels will have bogus
  244. * strings we don't care about, whereas new kernels will start right
  245. * out with MemTotal:
  246. * -- PFM.
  247. */
  248. if (fscanf(fp, "MemTotal: %lu %s\n", &total, buf) != 2) {
  249. fgets(buf, sizeof(buf), fp); /* skip first line */
  250. fscanf(fp, "Mem: %lu %lu %lu %lu %lu %lu",
  251. &total, &used, &mfree, &shared, &buffers, &cached);
  252. /* convert to kilobytes */
  253. used /= 1024;
  254. mfree /= 1024;
  255. shared /= 1024;
  256. buffers /= 1024;
  257. cached /= 1024;
  258. total /= 1024;
  259. } else {
  260. /*
  261. * Revert to manual parsing, which incidentally already has the
  262. * sizes in kilobytes. This should be safe for both 2.4 and
  263. * 2.6.
  264. */
  265. fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
  266. /*
  267. * MemShared: is no longer present in 2.6. Report this as 0,
  268. * to maintain consistent behavior with normal procps.
  269. */
  270. if (fscanf(fp, "MemShared: %lu %s\n", &shared, buf) != 2)
  271. shared = 0;
  272. fscanf(fp, "Buffers: %lu %s\n", &buffers, buf);
  273. fscanf(fp, "Cached: %lu %s\n", &cached, buf);
  274. used = total - mfree;
  275. }
  276. fclose(fp);
  277. /* output memory info */
  278. if (scr_width > sizeof(scrbuf))
  279. scr_width = sizeof(scrbuf);
  280. snprintf(scrbuf, scr_width,
  281. "Mem: %luK used, %luK free, %luK shrd, %luK buff, %luK cached",
  282. used, mfree, shared, buffers, cached);
  283. /* clear screen & go to top */
  284. printf(OPT_BATCH_MODE ? "%s\n" : "\e[H\e[J%s\n", scrbuf);
  285. #if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS
  286. /*
  287. * xxx% = (jif.xxx - prev_jif.xxx) / (jif.total - prev_jif.total) * 100%
  288. */
  289. /* using (unsigned) casts to make operations cheaper */
  290. total_diff = ((unsigned)(jif.total - prev_jif.total) ? : 1);
  291. #if ENABLE_FEATURE_TOP_DECIMALS
  292. /* Generated code is approx +0.3k */
  293. #define CALC_STAT(xxx) char xxx[8]
  294. #define SHOW_STAT(xxx) fmt_100percent_8(xxx, (unsigned)(jif.xxx - prev_jif.xxx), total_diff)
  295. #define FMT "%s"
  296. #else
  297. #define CALC_STAT(xxx) unsigned xxx = 100 * (unsigned)(jif.xxx - prev_jif.xxx) / total_diff
  298. #define SHOW_STAT(xxx) xxx
  299. #define FMT "%4u%% "
  300. #endif
  301. { /* need block: CALC_STAT are declarations */
  302. CALC_STAT(usr);
  303. CALC_STAT(sys);
  304. CALC_STAT(nic);
  305. CALC_STAT(idle);
  306. CALC_STAT(iowait);
  307. CALC_STAT(irq);
  308. CALC_STAT(softirq);
  309. //CALC_STAT(steal);
  310. snprintf(scrbuf, scr_width,
  311. /* Barely fits in 79 chars when in "decimals" mode. */
  312. "CPU:"FMT"usr"FMT"sys"FMT"nice"FMT"idle"FMT"io"FMT"irq"FMT"softirq",
  313. SHOW_STAT(usr), SHOW_STAT(sys), SHOW_STAT(nic), SHOW_STAT(idle),
  314. SHOW_STAT(iowait), SHOW_STAT(irq), SHOW_STAT(softirq)
  315. //, SHOW_STAT(steal) - what is this 'steal' thing?
  316. // I doubt anyone wants to know it
  317. );
  318. }
  319. puts(scrbuf);
  320. #undef SHOW_STAT
  321. #undef CALC_STAT
  322. #undef FMT
  323. #endif
  324. /* read load average as a string */
  325. buf[0] = '\0';
  326. open_read_close("loadavg", buf, sizeof("N.NN N.NN N.NN")-1);
  327. buf[sizeof("N.NN N.NN N.NN")-1] = '\0';
  328. snprintf(scrbuf, scr_width, "Load average: %s", buf);
  329. puts(scrbuf);
  330. return total;
  331. }
  332. static NOINLINE void display_process_list(int count, int scr_width)
  333. {
  334. enum {
  335. BITS_PER_INT = sizeof(int)*8
  336. };
  337. top_status_t *s = top;
  338. char vsz_str_buf[8];
  339. unsigned long total_memory = display_header(scr_width); /* or use total_vsz? */
  340. /* xxx_shift and xxx_scale variables allow us to replace
  341. * expensive divides with multiply and shift */
  342. unsigned pmem_shift, pmem_scale, pmem_half;
  343. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  344. unsigned pcpu_shift, pcpu_scale, pcpu_half;
  345. unsigned busy_jifs;
  346. /* what info of the processes is shown */
  347. printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
  348. " PID PPID USER STAT VSZ %MEM %CPU COMMAND");
  349. #else
  350. /* !CPU_USAGE_PERCENTAGE */
  351. printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
  352. " PID PPID USER STAT VSZ %MEM COMMAND");
  353. #endif
  354. #if ENABLE_FEATURE_TOP_DECIMALS
  355. #define UPSCALE 1000
  356. #define CALC_STAT(name, val) div_t name = div((val), 10)
  357. #define SHOW_STAT(name) name.quot, '0'+name.rem
  358. #define FMT "%3u.%c"
  359. #else
  360. #define UPSCALE 100
  361. #define CALC_STAT(name, val) unsigned name = (val)
  362. #define SHOW_STAT(name) name
  363. #define FMT "%4u%%"
  364. #endif
  365. /*
  366. * MEM% = s->vsz/MemTotal
  367. */
  368. pmem_shift = BITS_PER_INT-11;
  369. pmem_scale = UPSCALE*(1U<<(BITS_PER_INT-11)) / total_memory;
  370. /* s->vsz is in kb. we want (s->vsz * pmem_scale) to never overflow */
  371. while (pmem_scale >= 512) {
  372. pmem_scale /= 4;
  373. pmem_shift -= 2;
  374. }
  375. pmem_half = (1U << pmem_shift) / (ENABLE_FEATURE_TOP_DECIMALS? 20 : 2);
  376. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  377. busy_jifs = jif.busy - prev_jif.busy;
  378. /* This happens if there were lots of short-lived processes
  379. * between two top updates (e.g. compilation) */
  380. if (total_pcpu < busy_jifs) total_pcpu = busy_jifs;
  381. /*
  382. * CPU% = s->pcpu/sum(s->pcpu) * busy_cpu_ticks/total_cpu_ticks
  383. * (pcpu is delta of sys+user time between samples)
  384. */
  385. /* (jif.xxx - prev_jif.xxx) and s->pcpu are
  386. * in 0..~64000 range (HZ*update_interval).
  387. * we assume that unsigned is at least 32-bit.
  388. */
  389. pcpu_shift = 6;
  390. pcpu_scale = (UPSCALE*64*(uint16_t)busy_jifs ? : 1);
  391. while (pcpu_scale < (1U<<(BITS_PER_INT-2))) {
  392. pcpu_scale *= 4;
  393. pcpu_shift += 2;
  394. }
  395. pcpu_scale /= ( (uint16_t)(jif.total-prev_jif.total)*total_pcpu ? : 1);
  396. /* we want (s->pcpu * pcpu_scale) to never overflow */
  397. while (pcpu_scale >= 1024) {
  398. pcpu_scale /= 4;
  399. pcpu_shift -= 2;
  400. }
  401. pcpu_half = (1U << pcpu_shift) / (ENABLE_FEATURE_TOP_DECIMALS? 20 : 2);
  402. /* printf(" pmem_scale=%u pcpu_scale=%u ", pmem_scale, pcpu_scale); */
  403. #endif
  404. scr_width += 2; /* account for leading '\n' and trailing NUL */
  405. /* Ok, all preliminary data is ready, go through the list */
  406. while (count-- > 0) {
  407. unsigned col;
  408. CALC_STAT(pmem, (s->vsz*pmem_scale + pmem_half) >> pmem_shift);
  409. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  410. CALC_STAT(pcpu, (s->pcpu*pcpu_scale + pcpu_half) >> pcpu_shift);
  411. #endif
  412. if (s->vsz >= 100000)
  413. sprintf(vsz_str_buf, "%6ldm", s->vsz/1024);
  414. else
  415. sprintf(vsz_str_buf, "%7ld", s->vsz);
  416. // PID PPID USER STAT VSZ %MEM [%CPU] COMMAND
  417. col = snprintf(line_buf, scr_width,
  418. "\n" "%5u%6u %-8.8s %s%s" FMT
  419. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  420. FMT
  421. #endif
  422. " ",
  423. s->pid, s->ppid, get_cached_username(s->uid),
  424. s->state, vsz_str_buf,
  425. SHOW_STAT(pmem)
  426. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  427. , SHOW_STAT(pcpu)
  428. #endif
  429. );
  430. if (col + 1 < scr_width)
  431. read_cmdline(line_buf + col, scr_width - col - 1, s->pid, s->comm);
  432. fputs(line_buf, stdout);
  433. /* printf(" %d/%d %lld/%lld", s->pcpu, total_pcpu,
  434. jif.busy - prev_jif.busy, jif.total - prev_jif.total); */
  435. s++;
  436. }
  437. /* printf(" %d", hist_iterations); */
  438. bb_putchar(OPT_BATCH_MODE ? '\n' : '\r');
  439. fflush(stdout);
  440. }
  441. #undef UPSCALE
  442. #undef SHOW_STAT
  443. #undef CALC_STAT
  444. #undef FMT
  445. static void clearmems(void)
  446. {
  447. clear_username_cache();
  448. free(top);
  449. top = NULL;
  450. ntop = 0;
  451. }
  452. #if ENABLE_FEATURE_USE_TERMIOS
  453. #include <termios.h>
  454. #include <signal.h>
  455. static void reset_term(void)
  456. {
  457. tcsetattr(0, TCSANOW, &initial_settings);
  458. if (ENABLE_FEATURE_CLEAN_UP) {
  459. clearmems();
  460. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  461. free(prev_hist);
  462. #endif
  463. }
  464. }
  465. static void sig_catcher(int sig ATTRIBUTE_UNUSED)
  466. {
  467. reset_term();
  468. exit(1);
  469. }
  470. #endif /* FEATURE_USE_TERMIOS */
  471. /*
  472. * TOPMEM support
  473. */
  474. typedef unsigned long mem_t;
  475. typedef struct topmem_status_t {
  476. unsigned pid;
  477. char comm[COMM_LEN];
  478. /* vsz doesn't count /dev/xxx mappings except /dev/zero */
  479. mem_t vsz ;
  480. mem_t vszrw ;
  481. mem_t rss ;
  482. mem_t rss_sh ;
  483. mem_t dirty ;
  484. mem_t dirty_sh;
  485. mem_t stack ;
  486. } topmem_status_t;
  487. enum { NUM_SORT_FIELD = 7 };
  488. #define topmem ((topmem_status_t*)top)
  489. #if ENABLE_FEATURE_TOPMEM
  490. static int topmem_sort(char *a, char *b)
  491. {
  492. int n;
  493. mem_t l, r;
  494. n = offsetof(topmem_status_t, vsz) + (sort_field * sizeof(mem_t));
  495. l = *(mem_t*)(a + n);
  496. r = *(mem_t*)(b + n);
  497. // if (l == r) {
  498. // l = a->mapped_rw;
  499. // r = b->mapped_rw;
  500. // }
  501. /* We want to avoid unsigned->signed and truncation errors */
  502. /* l>r: -1, l=r: 0, l<r: 1 */
  503. n = (l > r) ? -1 : (l != r);
  504. return inverted ? -n : n;
  505. }
  506. /* Cut "NNNN " out of " NNNN kb" */
  507. static char *grab_number(char *str, const char *match, unsigned sz)
  508. {
  509. if (strncmp(str, match, sz) == 0) {
  510. str = skip_whitespace(str + sz);
  511. (skip_non_whitespace(str))[1] = '\0';
  512. return xstrdup(str);
  513. }
  514. return NULL;
  515. }
  516. /* display header info (meminfo / loadavg) */
  517. static void display_topmem_header(int scr_width)
  518. {
  519. char linebuf[128];
  520. int i;
  521. FILE *fp;
  522. union {
  523. struct {
  524. /* 1 */ char *total;
  525. /* 2 */ char *mfree;
  526. /* 3 */ char *buf;
  527. /* 4 */ char *cache;
  528. /* 5 */ char *swaptotal;
  529. /* 6 */ char *swapfree;
  530. /* 7 */ char *dirty;
  531. /* 8 */ char *mwrite;
  532. /* 9 */ char *anon;
  533. /* 10 */ char *map;
  534. /* 11 */ char *slab;
  535. } u;
  536. char *str[11];
  537. } Z;
  538. #define total Z.u.total
  539. #define mfree Z.u.mfree
  540. #define buf Z.u.buf
  541. #define cache Z.u.cache
  542. #define swaptotal Z.u.swaptotal
  543. #define swapfree Z.u.swapfree
  544. #define dirty Z.u.dirty
  545. #define mwrite Z.u.mwrite
  546. #define anon Z.u.anon
  547. #define map Z.u.map
  548. #define slab Z.u.slab
  549. #define str Z.str
  550. memset(&Z, 0, sizeof(Z));
  551. /* read memory info */
  552. fp = xfopen("meminfo", "r");
  553. while (fgets(linebuf, sizeof(linebuf), fp)) {
  554. char *p;
  555. #define SCAN(match, name) \
  556. p = grab_number(linebuf, match, sizeof(match)-1); \
  557. if (p) { name = p; continue; }
  558. SCAN("MemTotal:", total);
  559. SCAN("MemFree:", mfree);
  560. SCAN("Buffers:", buf);
  561. SCAN("Cached:", cache);
  562. SCAN("SwapTotal:", swaptotal);
  563. SCAN("SwapFree:", swapfree);
  564. SCAN("Dirty:", dirty);
  565. SCAN("Writeback:", mwrite);
  566. SCAN("AnonPages:", anon);
  567. SCAN("Mapped:", map);
  568. SCAN("Slab:", slab);
  569. #undef SCAN
  570. }
  571. fclose(fp);
  572. #define S(s) (s ? s : "0 ")
  573. snprintf(linebuf, sizeof(linebuf),
  574. "Mem %stotal %sanon %smap %sfree",
  575. S(total), S(anon), S(map), S(mfree));
  576. printf(OPT_BATCH_MODE ? "%.*s\n" : "\e[H\e[J%.*s\n", scr_width, linebuf);
  577. snprintf(linebuf, sizeof(linebuf),
  578. " %sslab %sbuf %scache %sdirty %swrite",
  579. S(slab), S(buf), S(cache), S(dirty), S(mwrite));
  580. printf("%.*s\n", scr_width, linebuf);
  581. snprintf(linebuf, sizeof(linebuf),
  582. "Swap %stotal %sfree", // TODO: % used?
  583. S(swaptotal), S(swapfree));
  584. printf("%.*s\n", scr_width, linebuf);
  585. #undef S
  586. for (i = 0; i < ARRAY_SIZE(str); i++)
  587. free(str[i]);
  588. #undef total
  589. #undef free
  590. #undef buf
  591. #undef cache
  592. #undef swaptotal
  593. #undef swapfree
  594. #undef dirty
  595. #undef write
  596. #undef anon
  597. #undef map
  598. #undef slab
  599. #undef str
  600. }
  601. static void ulltoa6_and_space(unsigned long long ul, char buf[6])
  602. {
  603. /* see http://en.wikipedia.org/wiki/Tera */
  604. smart_ulltoa5(ul, buf, " mgtpezy");
  605. buf[5] = ' ';
  606. }
  607. static NOINLINE void display_topmem_process_list(int count, int scr_width)
  608. {
  609. #define HDR_STR " PID VSZ VSZRW RSS (SHR) DIRTY (SHR) STACK"
  610. #define MIN_WIDTH sizeof(HDR_STR)
  611. const topmem_status_t *s = topmem;
  612. display_topmem_header(scr_width);
  613. strcpy(line_buf, HDR_STR " COMMAND");
  614. line_buf[5 + sort_field * 6] = '*';
  615. printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width, line_buf);
  616. while (--count >= 0) {
  617. // PID VSZ VSZRW RSS (SHR) DIRTY (SHR) COMMAND
  618. ulltoa6_and_space(s->pid , &line_buf[0*6]);
  619. ulltoa6_and_space(s->vsz , &line_buf[1*6]);
  620. ulltoa6_and_space(s->vszrw , &line_buf[2*6]);
  621. ulltoa6_and_space(s->rss , &line_buf[3*6]);
  622. ulltoa6_and_space(s->rss_sh , &line_buf[4*6]);
  623. ulltoa6_and_space(s->dirty , &line_buf[5*6]);
  624. ulltoa6_and_space(s->dirty_sh, &line_buf[6*6]);
  625. ulltoa6_and_space(s->stack , &line_buf[7*6]);
  626. line_buf[8*6] = '\0';
  627. if (scr_width > MIN_WIDTH) {
  628. read_cmdline(&line_buf[8*6], scr_width - MIN_WIDTH, s->pid, s->comm);
  629. }
  630. printf("\n""%.*s", scr_width, line_buf);
  631. s++;
  632. }
  633. bb_putchar(OPT_BATCH_MODE ? '\n' : '\r');
  634. fflush(stdout);
  635. #undef HDR_STR
  636. #undef MIN_WIDTH
  637. }
  638. #else
  639. void display_topmem_process_list(int count, int scr_width);
  640. int topmem_sort(char *a, char *b);
  641. #endif /* TOPMEM */
  642. /*
  643. * end TOPMEM support
  644. */
  645. enum {
  646. TOP_MASK = 0
  647. | PSSCAN_PID
  648. | PSSCAN_PPID
  649. | PSSCAN_VSZ
  650. | PSSCAN_STIME
  651. | PSSCAN_UTIME
  652. | PSSCAN_STATE
  653. | PSSCAN_COMM
  654. | PSSCAN_UIDGID,
  655. TOPMEM_MASK = 0
  656. | PSSCAN_PID
  657. | PSSCAN_SMAPS
  658. | PSSCAN_COMM,
  659. };
  660. int top_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  661. int top_main(int argc ATTRIBUTE_UNUSED, char **argv)
  662. {
  663. int count, lines, col;
  664. unsigned interval;
  665. int iterations;
  666. char *sinterval;
  667. SKIP_FEATURE_TOPMEM(const) unsigned scan_mask = TOP_MASK;
  668. #if ENABLE_FEATURE_USE_TERMIOS
  669. struct termios new_settings;
  670. struct pollfd pfd[1];
  671. unsigned char c;
  672. pfd[0].fd = 0;
  673. pfd[0].events = POLLIN;
  674. #endif /* FEATURE_USE_TERMIOS */
  675. INIT_G();
  676. interval = 5; /* default update interval is 5 seconds */
  677. iterations = 0; /* infinite */
  678. /* all args are options; -n NUM */
  679. opt_complementary = "-:n+";
  680. getopt32(argv, "d:n:b", &sinterval, &iterations);
  681. if (option_mask32 & OPT_d) {
  682. /* Need to limit it to not overflow poll timeout */
  683. interval = xatou16(sinterval); // -d
  684. }
  685. /* change to /proc */
  686. xchdir("/proc");
  687. #if ENABLE_FEATURE_USE_TERMIOS
  688. tcgetattr(0, (void *) &initial_settings);
  689. memcpy(&new_settings, &initial_settings, sizeof(new_settings));
  690. /* unbuffered input, turn off echo */
  691. new_settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHONL);
  692. bb_signals(BB_FATAL_SIGS, sig_catcher);
  693. tcsetattr(0, TCSANOW, (void *) &new_settings);
  694. #endif /* FEATURE_USE_TERMIOS */
  695. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  696. sort_function[0] = pcpu_sort;
  697. sort_function[1] = mem_sort;
  698. sort_function[2] = time_sort;
  699. #else
  700. sort_function[0] = mem_sort;
  701. #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
  702. while (1) {
  703. procps_status_t *p = NULL;
  704. lines = 24; /* default */
  705. col = 79;
  706. #if ENABLE_FEATURE_USE_TERMIOS
  707. /* We output to stdout, we need size of stdout (not stdin)! */
  708. get_terminal_width_height(STDOUT_FILENO, &col, &lines);
  709. if (lines < 5 || col < 10) {
  710. sleep(interval);
  711. continue;
  712. }
  713. #endif /* FEATURE_USE_TERMIOS */
  714. if (col > LINE_BUF_SIZE-2) /* +2 bytes for '\n', NUL, */
  715. col = LINE_BUF_SIZE-2;
  716. if (!ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS && scan_mask == TOP_MASK)
  717. lines -= 3;
  718. else
  719. lines -= 4;
  720. /* read process IDs & status for all the processes */
  721. while ((p = procps_scan(p, scan_mask)) != NULL) {
  722. int n;
  723. if (scan_mask == TOP_MASK) {
  724. n = ntop;
  725. top = xrealloc(top, (++ntop) * sizeof(*top));
  726. top[n].pid = p->pid;
  727. top[n].ppid = p->ppid;
  728. top[n].vsz = p->vsz;
  729. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  730. top[n].ticks = p->stime + p->utime;
  731. #endif
  732. top[n].uid = p->uid;
  733. strcpy(top[n].state, p->state);
  734. strcpy(top[n].comm, p->comm);
  735. } else { /* TOPMEM */
  736. #if ENABLE_FEATURE_TOPMEM
  737. if (!(p->mapped_ro | p->mapped_rw))
  738. continue; /* kernel threads are ignored */
  739. n = ntop;
  740. top = xrealloc(topmem, (++ntop) * sizeof(*topmem));
  741. strcpy(topmem[n].comm, p->comm);
  742. topmem[n].pid = p->pid;
  743. topmem[n].vsz = p->mapped_rw + p->mapped_ro;
  744. topmem[n].vszrw = p->mapped_rw;
  745. topmem[n].rss_sh = p->shared_clean + p->shared_dirty;
  746. topmem[n].rss = p->private_clean + p->private_dirty + topmem[n].rss_sh;
  747. topmem[n].dirty = p->private_dirty + p->shared_dirty;
  748. topmem[n].dirty_sh = p->shared_dirty;
  749. topmem[n].stack = p->stack;
  750. #endif
  751. }
  752. } /* end of "while we read /proc" */
  753. if (ntop == 0) {
  754. bb_error_msg("no process info in /proc");
  755. break;
  756. }
  757. if (scan_mask == TOP_MASK) {
  758. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  759. if (!prev_hist_count) {
  760. do_stats();
  761. usleep(100000);
  762. clearmems();
  763. continue;
  764. }
  765. do_stats();
  766. /* TODO: we don't need to sort all 10000 processes, we need to find top 24! */
  767. qsort(top, ntop, sizeof(top_status_t), (void*)mult_lvl_cmp);
  768. #else
  769. qsort(top, ntop, sizeof(top_status_t), (void*)(sort_function[0]));
  770. #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
  771. }
  772. #if ENABLE_FEATURE_TOPMEM
  773. else { /* TOPMEM */
  774. qsort(topmem, ntop, sizeof(topmem_status_t), (void*)topmem_sort);
  775. }
  776. #endif
  777. count = lines;
  778. if (OPT_BATCH_MODE || count > ntop) {
  779. count = ntop;
  780. }
  781. if (scan_mask == TOP_MASK)
  782. display_process_list(count, col);
  783. #if ENABLE_FEATURE_TOPMEM
  784. else
  785. display_topmem_process_list(count, col);
  786. #endif
  787. clearmems();
  788. if (iterations >= 0 && !--iterations)
  789. break;
  790. #if !ENABLE_FEATURE_USE_TERMIOS
  791. sleep(interval);
  792. #else
  793. if (option_mask32 & (OPT_b|OPT_EOF))
  794. /* batch mode, or EOF on stdin ("top </dev/null") */
  795. sleep(interval);
  796. else if (safe_poll(pfd, 1, interval * 1000) > 0) {
  797. if (safe_read(0, &c, 1) != 1) { /* error/EOF? */
  798. option_mask32 |= OPT_EOF;
  799. continue;
  800. }
  801. if (c == initial_settings.c_cc[VINTR])
  802. break;
  803. c |= 0x20; /* lowercase */
  804. if (c == 'q')
  805. break;
  806. if (c == 'n') {
  807. USE_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
  808. sort_function[0] = pid_sort;
  809. }
  810. if (c == 'm') {
  811. USE_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
  812. sort_function[0] = mem_sort;
  813. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  814. sort_function[1] = pcpu_sort;
  815. sort_function[2] = time_sort;
  816. #endif
  817. }
  818. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  819. if (c == 'p') {
  820. USE_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
  821. sort_function[0] = pcpu_sort;
  822. sort_function[1] = mem_sort;
  823. sort_function[2] = time_sort;
  824. }
  825. if (c == 't') {
  826. USE_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
  827. sort_function[0] = time_sort;
  828. sort_function[1] = mem_sort;
  829. sort_function[2] = pcpu_sort;
  830. }
  831. #if ENABLE_FEATURE_TOPMEM
  832. if (c == 's') {
  833. scan_mask = TOPMEM_MASK;
  834. free(prev_hist);
  835. prev_hist = NULL;
  836. prev_hist_count = 0;
  837. sort_field = (sort_field + 1) % NUM_SORT_FIELD;
  838. }
  839. if (c == 'r')
  840. inverted ^= 1;
  841. #endif
  842. #endif
  843. }
  844. #endif /* FEATURE_USE_TERMIOS */
  845. } /* end of "while (1)" */
  846. bb_putchar('\n');
  847. #if ENABLE_FEATURE_USE_TERMIOS
  848. reset_term();
  849. #endif
  850. return EXIT_SUCCESS;
  851. }