top.c 24 KB

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