top.c 25 KB

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