top.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  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. *
  8. * This reads the PIDs of all processes and their status and shows
  9. * the status of processes (first ones that fit to screen) at given
  10. * intervals.
  11. *
  12. * NOTES:
  13. * - At startup this changes to /proc, all the reads are then
  14. * relative to that.
  15. *
  16. * (C) Eero Tamminen <oak at welho dot com>
  17. *
  18. * Rewritten by Vladimir Oleynik (C) 2002 <dzo@simtreas.ru>
  19. *
  20. * Sept 2008: Vineet Gupta <vineet.gupta@arc.com>
  21. * Added Support for reporting SMP Information
  22. * - CPU where process was last seen running
  23. * (to see effect of sched_setaffinity() etc)
  24. * - CPU time split (idle/IO/wait etc) per CPU
  25. *
  26. * Copyright (c) 1992 Branko Lankester
  27. * Copyright (c) 1992 Roger Binns
  28. * Copyright (C) 1994-1996 Charles L. Blake.
  29. * Copyright (C) 1992-1998 Michael K. Johnson
  30. *
  31. * Licensed under GPLv2, see file LICENSE in this source tree.
  32. */
  33. /* How to snapshot /proc for debugging top problems:
  34. * for f in /proc/[0-9]*""/stat; do
  35. * n=${f#/proc/}
  36. * n=${n%/stat}_stat
  37. * cp $f $n
  38. * done
  39. * cp /proc/stat /proc/meminfo /proc/loadavg .
  40. * top -bn1 >top.out
  41. *
  42. * ...and how to run top on it on another machine:
  43. * rm -rf proc; mkdir proc
  44. * for f in [0-9]*_stat; do
  45. * p=${f%_stat}
  46. * mkdir -p proc/$p
  47. * cp $f proc/$p/stat
  48. * done
  49. * cp stat meminfo loadavg proc
  50. * chroot . ./top -bn1 >top1.out
  51. */
  52. //config:config TOP
  53. //config: bool "top"
  54. //config: default y
  55. //config: help
  56. //config: The top program provides a dynamic real-time view of a running
  57. //config: system.
  58. //config:
  59. //config:config FEATURE_TOP_CPU_USAGE_PERCENTAGE
  60. //config: bool "Show CPU per-process usage percentage"
  61. //config: default y
  62. //config: depends on TOP
  63. //config: help
  64. //config: Make top display CPU usage for each process.
  65. //config: This adds about 2k.
  66. //config:
  67. //config:config FEATURE_TOP_CPU_GLOBAL_PERCENTS
  68. //config: bool "Show CPU global usage percentage"
  69. //config: default y
  70. //config: depends on FEATURE_TOP_CPU_USAGE_PERCENTAGE
  71. //config: help
  72. //config: Makes top display "CPU: NN% usr NN% sys..." line.
  73. //config: This adds about 0.5k.
  74. //config:
  75. //config:config FEATURE_TOP_SMP_CPU
  76. //config: bool "SMP CPU usage display ('c' key)"
  77. //config: default y
  78. //config: depends on FEATURE_TOP_CPU_GLOBAL_PERCENTS
  79. //config: help
  80. //config: Allow 'c' key to switch between individual/cumulative CPU stats
  81. //config: This adds about 0.5k.
  82. //config:
  83. //config:config FEATURE_TOP_DECIMALS
  84. //config: bool "Show 1/10th of a percent in CPU/mem statistics"
  85. //config: default y
  86. //config: depends on FEATURE_TOP_CPU_USAGE_PERCENTAGE
  87. //config: help
  88. //config: Show 1/10th of a percent in CPU/mem statistics.
  89. //config: This adds about 0.3k.
  90. //config:
  91. //config:config FEATURE_TOP_SMP_PROCESS
  92. //config: bool "Show CPU process runs on ('j' field)"
  93. //config: default y
  94. //config: depends on TOP
  95. //config: help
  96. //config: Show CPU where process was last found running on.
  97. //config: This is the 'j' field.
  98. //config:
  99. //config:config FEATURE_TOPMEM
  100. //config: bool "Topmem command ('s' key)"
  101. //config: default y
  102. //config: depends on TOP
  103. //config: help
  104. //config: Enable 's' in top (gives lots of memory info).
  105. #include "libbb.h"
  106. typedef struct top_status_t {
  107. unsigned long vsz;
  108. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  109. unsigned long ticks;
  110. unsigned pcpu; /* delta of ticks */
  111. #endif
  112. unsigned pid, ppid;
  113. unsigned uid;
  114. char state[4];
  115. char comm[COMM_LEN];
  116. #if ENABLE_FEATURE_TOP_SMP_PROCESS
  117. int last_seen_on_cpu;
  118. #endif
  119. } top_status_t;
  120. typedef struct jiffy_counts_t {
  121. /* Linux 2.4.x has only first four */
  122. unsigned long long usr, nic, sys, idle;
  123. unsigned long long iowait, irq, softirq, steal;
  124. unsigned long long total;
  125. unsigned long long busy;
  126. } jiffy_counts_t;
  127. /* This structure stores some critical information from one frame to
  128. the next. Used for finding deltas. */
  129. typedef struct save_hist {
  130. unsigned long ticks;
  131. pid_t pid;
  132. } save_hist;
  133. typedef int (*cmp_funcp)(top_status_t *P, top_status_t *Q);
  134. enum { SORT_DEPTH = 3 };
  135. struct globals {
  136. top_status_t *top;
  137. int ntop;
  138. smallint inverted;
  139. #if ENABLE_FEATURE_TOPMEM
  140. smallint sort_field;
  141. #endif
  142. #if ENABLE_FEATURE_TOP_SMP_CPU
  143. smallint smp_cpu_info; /* one/many cpu info lines? */
  144. #endif
  145. unsigned lines; /* screen height */
  146. #if ENABLE_FEATURE_USE_TERMIOS
  147. struct termios initial_settings;
  148. int scroll_ofs;
  149. #define G_scroll_ofs G.scroll_ofs
  150. #else
  151. #define G_scroll_ofs 0
  152. #endif
  153. #if !ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  154. cmp_funcp sort_function[1];
  155. #else
  156. cmp_funcp sort_function[SORT_DEPTH];
  157. struct save_hist *prev_hist;
  158. int prev_hist_count;
  159. jiffy_counts_t cur_jif, prev_jif;
  160. /* int hist_iterations; */
  161. unsigned total_pcpu;
  162. /* unsigned long total_vsz; */
  163. #endif
  164. #if ENABLE_FEATURE_TOP_SMP_CPU
  165. /* Per CPU samples: current and last */
  166. jiffy_counts_t *cpu_jif, *cpu_prev_jif;
  167. int num_cpus;
  168. #endif
  169. #if ENABLE_FEATURE_USE_TERMIOS
  170. char kbd_input[KEYCODE_BUFFER_SIZE];
  171. #endif
  172. char line_buf[80];
  173. }; //FIX_ALIASING; - large code growth
  174. enum { LINE_BUF_SIZE = COMMON_BUFSIZE - offsetof(struct globals, line_buf) };
  175. #define G (*(struct globals*)&bb_common_bufsiz1)
  176. struct BUG_bad_size {
  177. char BUG_G_too_big[sizeof(G) <= COMMON_BUFSIZE ? 1 : -1];
  178. char BUG_line_buf_too_small[LINE_BUF_SIZE > 80 ? 1 : -1];
  179. };
  180. #define top (G.top )
  181. #define ntop (G.ntop )
  182. #define sort_field (G.sort_field )
  183. #define inverted (G.inverted )
  184. #define smp_cpu_info (G.smp_cpu_info )
  185. #define initial_settings (G.initial_settings )
  186. #define sort_function (G.sort_function )
  187. #define prev_hist (G.prev_hist )
  188. #define prev_hist_count (G.prev_hist_count )
  189. #define cur_jif (G.cur_jif )
  190. #define prev_jif (G.prev_jif )
  191. #define cpu_jif (G.cpu_jif )
  192. #define cpu_prev_jif (G.cpu_prev_jif )
  193. #define num_cpus (G.num_cpus )
  194. #define total_pcpu (G.total_pcpu )
  195. #define line_buf (G.line_buf )
  196. #define INIT_G() do { } while (0)
  197. enum {
  198. OPT_d = (1 << 0),
  199. OPT_n = (1 << 1),
  200. OPT_b = (1 << 2),
  201. OPT_m = (1 << 3),
  202. OPT_EOF = (1 << 4), /* pseudo: "we saw EOF in stdin" */
  203. };
  204. #define OPT_BATCH_MODE (option_mask32 & OPT_b)
  205. #if ENABLE_FEATURE_USE_TERMIOS
  206. static int pid_sort(top_status_t *P, top_status_t *Q)
  207. {
  208. /* Buggy wrt pids with high bit set */
  209. /* (linux pids are in [1..2^15-1]) */
  210. return (Q->pid - P->pid);
  211. }
  212. #endif
  213. static int mem_sort(top_status_t *P, top_status_t *Q)
  214. {
  215. /* We want to avoid unsigned->signed and truncation errors */
  216. if (Q->vsz < P->vsz) return -1;
  217. return Q->vsz != P->vsz; /* 0 if ==, 1 if > */
  218. }
  219. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  220. static int pcpu_sort(top_status_t *P, top_status_t *Q)
  221. {
  222. /* Buggy wrt ticks with high bit set */
  223. /* Affects only processes for which ticks overflow */
  224. return (int)Q->pcpu - (int)P->pcpu;
  225. }
  226. static int time_sort(top_status_t *P, top_status_t *Q)
  227. {
  228. /* We want to avoid unsigned->signed and truncation errors */
  229. if (Q->ticks < P->ticks) return -1;
  230. return Q->ticks != P->ticks; /* 0 if ==, 1 if > */
  231. }
  232. static int mult_lvl_cmp(void* a, void* b)
  233. {
  234. int i, cmp_val;
  235. for (i = 0; i < SORT_DEPTH; i++) {
  236. cmp_val = (*sort_function[i])(a, b);
  237. if (cmp_val != 0)
  238. break;
  239. }
  240. return inverted ? -cmp_val : cmp_val;
  241. }
  242. static NOINLINE int read_cpu_jiffy(FILE *fp, jiffy_counts_t *p_jif)
  243. {
  244. #if !ENABLE_FEATURE_TOP_SMP_CPU
  245. static const char fmt[] = "cpu %llu %llu %llu %llu %llu %llu %llu %llu";
  246. #else
  247. static const char fmt[] = "cp%*s %llu %llu %llu %llu %llu %llu %llu %llu";
  248. #endif
  249. int ret;
  250. if (!fgets(line_buf, LINE_BUF_SIZE, fp) || line_buf[0] != 'c' /* not "cpu" */)
  251. return 0;
  252. ret = sscanf(line_buf, fmt,
  253. &p_jif->usr, &p_jif->nic, &p_jif->sys, &p_jif->idle,
  254. &p_jif->iowait, &p_jif->irq, &p_jif->softirq,
  255. &p_jif->steal);
  256. if (ret >= 4) {
  257. p_jif->total = p_jif->usr + p_jif->nic + p_jif->sys + p_jif->idle
  258. + p_jif->iowait + p_jif->irq + p_jif->softirq + p_jif->steal;
  259. /* procps 2.x does not count iowait as busy time */
  260. p_jif->busy = p_jif->total - p_jif->idle - p_jif->iowait;
  261. }
  262. return ret;
  263. }
  264. static void get_jiffy_counts(void)
  265. {
  266. FILE* fp = xfopen_for_read("stat");
  267. /* We need to parse cumulative counts even if SMP CPU display is on,
  268. * they are used to calculate per process CPU% */
  269. prev_jif = cur_jif;
  270. if (read_cpu_jiffy(fp, &cur_jif) < 4)
  271. bb_error_msg_and_die("can't read '%s'", "/proc/stat");
  272. #if !ENABLE_FEATURE_TOP_SMP_CPU
  273. fclose(fp);
  274. return;
  275. #else
  276. if (!smp_cpu_info) {
  277. fclose(fp);
  278. return;
  279. }
  280. if (!num_cpus) {
  281. /* First time here. How many CPUs?
  282. * There will be at least 1 /proc/stat line with cpu%d
  283. */
  284. while (1) {
  285. cpu_jif = xrealloc_vector(cpu_jif, 1, num_cpus);
  286. if (read_cpu_jiffy(fp, &cpu_jif[num_cpus]) <= 4)
  287. break;
  288. num_cpus++;
  289. }
  290. if (num_cpus == 0) /* /proc/stat with only "cpu ..." line?! */
  291. smp_cpu_info = 0;
  292. cpu_prev_jif = xzalloc(sizeof(cpu_prev_jif[0]) * num_cpus);
  293. /* Otherwise the first per cpu display shows all 100% idles */
  294. usleep(50000);
  295. } else { /* Non first time invocation */
  296. jiffy_counts_t *tmp;
  297. int i;
  298. /* First switch the sample pointers: no need to copy */
  299. tmp = cpu_prev_jif;
  300. cpu_prev_jif = cpu_jif;
  301. cpu_jif = tmp;
  302. /* Get the new samples */
  303. for (i = 0; i < num_cpus; i++)
  304. read_cpu_jiffy(fp, &cpu_jif[i]);
  305. }
  306. #endif
  307. fclose(fp);
  308. }
  309. static void do_stats(void)
  310. {
  311. top_status_t *cur;
  312. pid_t pid;
  313. int i, last_i, n;
  314. struct save_hist *new_hist;
  315. get_jiffy_counts();
  316. total_pcpu = 0;
  317. /* total_vsz = 0; */
  318. new_hist = xmalloc(sizeof(new_hist[0]) * ntop);
  319. /*
  320. * Make a pass through the data to get stats.
  321. */
  322. /* hist_iterations = 0; */
  323. i = 0;
  324. for (n = 0; n < ntop; n++) {
  325. cur = top + n;
  326. /*
  327. * Calculate time in cur process. Time is sum of user time
  328. * and system time
  329. */
  330. pid = cur->pid;
  331. new_hist[n].ticks = cur->ticks;
  332. new_hist[n].pid = pid;
  333. /* find matching entry from previous pass */
  334. cur->pcpu = 0;
  335. /* do not start at index 0, continue at last used one
  336. * (brought hist_iterations from ~14000 down to 172) */
  337. last_i = i;
  338. if (prev_hist_count) do {
  339. if (prev_hist[i].pid == pid) {
  340. cur->pcpu = cur->ticks - prev_hist[i].ticks;
  341. total_pcpu += cur->pcpu;
  342. break;
  343. }
  344. i = (i+1) % prev_hist_count;
  345. /* hist_iterations++; */
  346. } while (i != last_i);
  347. /* total_vsz += cur->vsz; */
  348. }
  349. /*
  350. * Save cur frame's information.
  351. */
  352. free(prev_hist);
  353. prev_hist = new_hist;
  354. prev_hist_count = ntop;
  355. }
  356. #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
  357. #if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS && ENABLE_FEATURE_TOP_DECIMALS
  358. /* formats 7 char string (8 with terminating NUL) */
  359. static char *fmt_100percent_8(char pbuf[8], unsigned value, unsigned total)
  360. {
  361. unsigned t;
  362. if (value >= total) { /* 100% ? */
  363. strcpy(pbuf, " 100% ");
  364. return pbuf;
  365. }
  366. /* else generate " [N/space]N.N% " string */
  367. value = 1000 * value / total;
  368. t = value / 100;
  369. value = value % 100;
  370. pbuf[0] = ' ';
  371. pbuf[1] = t ? t + '0' : ' ';
  372. pbuf[2] = '0' + (value / 10);
  373. pbuf[3] = '.';
  374. pbuf[4] = '0' + (value % 10);
  375. pbuf[5] = '%';
  376. pbuf[6] = ' ';
  377. pbuf[7] = '\0';
  378. return pbuf;
  379. }
  380. #endif
  381. #if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS
  382. static void display_cpus(int scr_width, char *scrbuf, int *lines_rem_p)
  383. {
  384. /*
  385. * xxx% = (cur_jif.xxx - prev_jif.xxx) / (cur_jif.total - prev_jif.total) * 100%
  386. */
  387. unsigned total_diff;
  388. jiffy_counts_t *p_jif, *p_prev_jif;
  389. int i;
  390. # if ENABLE_FEATURE_TOP_SMP_CPU
  391. int n_cpu_lines;
  392. # endif
  393. /* using (unsigned) casts to make operations cheaper */
  394. # define CALC_TOTAL_DIFF do { \
  395. total_diff = (unsigned)(p_jif->total - p_prev_jif->total); \
  396. if (total_diff == 0) total_diff = 1; \
  397. } while (0)
  398. # if ENABLE_FEATURE_TOP_DECIMALS
  399. # define CALC_STAT(xxx) char xxx[8]
  400. # define SHOW_STAT(xxx) fmt_100percent_8(xxx, (unsigned)(p_jif->xxx - p_prev_jif->xxx), total_diff)
  401. # define FMT "%s"
  402. # else
  403. # define CALC_STAT(xxx) unsigned xxx = 100 * (unsigned)(p_jif->xxx - p_prev_jif->xxx) / total_diff
  404. # define SHOW_STAT(xxx) xxx
  405. # define FMT "%4u%% "
  406. # endif
  407. # if !ENABLE_FEATURE_TOP_SMP_CPU
  408. {
  409. i = 1;
  410. p_jif = &cur_jif;
  411. p_prev_jif = &prev_jif;
  412. # else
  413. /* Loop thru CPU(s) */
  414. n_cpu_lines = smp_cpu_info ? num_cpus : 1;
  415. if (n_cpu_lines > *lines_rem_p)
  416. n_cpu_lines = *lines_rem_p;
  417. for (i = 0; i < n_cpu_lines; i++) {
  418. p_jif = &cpu_jif[i];
  419. p_prev_jif = &cpu_prev_jif[i];
  420. # endif
  421. CALC_TOTAL_DIFF;
  422. { /* Need a block: CALC_STAT are declarations */
  423. CALC_STAT(usr);
  424. CALC_STAT(sys);
  425. CALC_STAT(nic);
  426. CALC_STAT(idle);
  427. CALC_STAT(iowait);
  428. CALC_STAT(irq);
  429. CALC_STAT(softirq);
  430. /*CALC_STAT(steal);*/
  431. snprintf(scrbuf, scr_width,
  432. /* Barely fits in 79 chars when in "decimals" mode. */
  433. # if ENABLE_FEATURE_TOP_SMP_CPU
  434. "CPU%s:"FMT"usr"FMT"sys"FMT"nic"FMT"idle"FMT"io"FMT"irq"FMT"sirq",
  435. (smp_cpu_info ? utoa(i) : ""),
  436. # else
  437. "CPU:"FMT"usr"FMT"sys"FMT"nic"FMT"idle"FMT"io"FMT"irq"FMT"sirq",
  438. # endif
  439. SHOW_STAT(usr), SHOW_STAT(sys), SHOW_STAT(nic), SHOW_STAT(idle),
  440. SHOW_STAT(iowait), SHOW_STAT(irq), SHOW_STAT(softirq)
  441. /*, SHOW_STAT(steal) - what is this 'steal' thing? */
  442. /* I doubt anyone wants to know it */
  443. );
  444. puts(scrbuf);
  445. }
  446. }
  447. # undef SHOW_STAT
  448. # undef CALC_STAT
  449. # undef FMT
  450. *lines_rem_p -= i;
  451. }
  452. #else /* !ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS */
  453. # define display_cpus(scr_width, scrbuf, lines_rem) ((void)0)
  454. #endif
  455. static unsigned long display_header(int scr_width, int *lines_rem_p)
  456. {
  457. FILE *fp;
  458. char buf[80];
  459. char scrbuf[80];
  460. unsigned long total, used, mfree, shared, buffers, cached;
  461. /* read memory info */
  462. fp = xfopen_for_read("meminfo");
  463. /*
  464. * Old kernels (such as 2.4.x) had a nice summary of memory info that
  465. * we could parse, however this is gone entirely in 2.6. Try parsing
  466. * the old way first, and if that fails, parse each field manually.
  467. *
  468. * First, we read in the first line. Old kernels will have bogus
  469. * strings we don't care about, whereas new kernels will start right
  470. * out with MemTotal:
  471. * -- PFM.
  472. */
  473. if (fscanf(fp, "MemTotal: %lu %s\n", &total, buf) != 2) {
  474. fgets(buf, sizeof(buf), fp); /* skip first line */
  475. fscanf(fp, "Mem: %lu %lu %lu %lu %lu %lu",
  476. &total, &used, &mfree, &shared, &buffers, &cached);
  477. /* convert to kilobytes */
  478. used /= 1024;
  479. mfree /= 1024;
  480. shared /= 1024;
  481. buffers /= 1024;
  482. cached /= 1024;
  483. total /= 1024;
  484. } else {
  485. /*
  486. * Revert to manual parsing, which incidentally already has the
  487. * sizes in kilobytes. This should be safe for both 2.4 and
  488. * 2.6.
  489. */
  490. fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
  491. /*
  492. * MemShared: is no longer present in 2.6. Report this as 0,
  493. * to maintain consistent behavior with normal procps.
  494. */
  495. if (fscanf(fp, "MemShared: %lu %s\n", &shared, buf) != 2)
  496. shared = 0;
  497. fscanf(fp, "Buffers: %lu %s\n", &buffers, buf);
  498. fscanf(fp, "Cached: %lu %s\n", &cached, buf);
  499. used = total - mfree;
  500. }
  501. fclose(fp);
  502. /* output memory info */
  503. if (scr_width > (int)sizeof(scrbuf))
  504. scr_width = sizeof(scrbuf);
  505. snprintf(scrbuf, scr_width,
  506. "Mem: %luK used, %luK free, %luK shrd, %luK buff, %luK cached",
  507. used, mfree, shared, buffers, cached);
  508. /* go to top & clear to the end of screen */
  509. printf(OPT_BATCH_MODE ? "%s\n" : "\033[H\033[J%s\n", scrbuf);
  510. (*lines_rem_p)--;
  511. /* Display CPU time split as percentage of total time
  512. * This displays either a cumulative line or one line per CPU
  513. */
  514. display_cpus(scr_width, scrbuf, lines_rem_p);
  515. /* read load average as a string */
  516. buf[0] = '\0';
  517. open_read_close("loadavg", buf, sizeof(buf) - 1);
  518. buf[sizeof(buf) - 1] = '\n';
  519. *strchr(buf, '\n') = '\0';
  520. snprintf(scrbuf, scr_width, "Load average: %s", buf);
  521. puts(scrbuf);
  522. (*lines_rem_p)--;
  523. return total;
  524. }
  525. static NOINLINE void display_process_list(int lines_rem, int scr_width)
  526. {
  527. enum {
  528. BITS_PER_INT = sizeof(int) * 8
  529. };
  530. top_status_t *s;
  531. char vsz_str_buf[8];
  532. unsigned long total_memory = display_header(scr_width, &lines_rem); /* or use total_vsz? */
  533. /* xxx_shift and xxx_scale variables allow us to replace
  534. * expensive divides with multiply and shift */
  535. unsigned pmem_shift, pmem_scale, pmem_half;
  536. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  537. unsigned tmp_unsigned;
  538. unsigned pcpu_shift, pcpu_scale, pcpu_half;
  539. unsigned busy_jifs;
  540. #endif
  541. /* what info of the processes is shown */
  542. printf(OPT_BATCH_MODE ? "%.*s" : "\033[7m%.*s\033[0m", scr_width,
  543. " PID PPID USER STAT VSZ %VSZ"
  544. IF_FEATURE_TOP_SMP_PROCESS(" CPU")
  545. IF_FEATURE_TOP_CPU_USAGE_PERCENTAGE(" %CPU")
  546. " COMMAND");
  547. lines_rem--;
  548. #if ENABLE_FEATURE_TOP_DECIMALS
  549. # define UPSCALE 1000
  550. # define CALC_STAT(name, val) div_t name = div((val), 10)
  551. # define SHOW_STAT(name) name.quot, '0'+name.rem
  552. # define FMT "%3u.%c"
  553. #else
  554. # define UPSCALE 100
  555. # define CALC_STAT(name, val) unsigned name = (val)
  556. # define SHOW_STAT(name) name
  557. # define FMT "%4u%%"
  558. #endif
  559. /*
  560. * %VSZ = s->vsz/MemTotal
  561. */
  562. pmem_shift = BITS_PER_INT-11;
  563. pmem_scale = UPSCALE*(1U<<(BITS_PER_INT-11)) / total_memory;
  564. /* s->vsz is in kb. we want (s->vsz * pmem_scale) to never overflow */
  565. while (pmem_scale >= 512) {
  566. pmem_scale /= 4;
  567. pmem_shift -= 2;
  568. }
  569. pmem_half = (1U << pmem_shift) / (ENABLE_FEATURE_TOP_DECIMALS ? 20 : 2);
  570. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  571. busy_jifs = cur_jif.busy - prev_jif.busy;
  572. /* This happens if there were lots of short-lived processes
  573. * between two top updates (e.g. compilation) */
  574. if (total_pcpu < busy_jifs) total_pcpu = busy_jifs;
  575. /*
  576. * CPU% = s->pcpu/sum(s->pcpu) * busy_cpu_ticks/total_cpu_ticks
  577. * (pcpu is delta of sys+user time between samples)
  578. */
  579. /* (cur_jif.xxx - prev_jif.xxx) and s->pcpu are
  580. * in 0..~64000 range (HZ*update_interval).
  581. * we assume that unsigned is at least 32-bit.
  582. */
  583. pcpu_shift = 6;
  584. pcpu_scale = UPSCALE*64 * (uint16_t)busy_jifs;
  585. if (pcpu_scale == 0)
  586. pcpu_scale = 1;
  587. while (pcpu_scale < (1U << (BITS_PER_INT-2))) {
  588. pcpu_scale *= 4;
  589. pcpu_shift += 2;
  590. }
  591. tmp_unsigned = (uint16_t)(cur_jif.total - prev_jif.total) * total_pcpu;
  592. if (tmp_unsigned != 0)
  593. pcpu_scale /= tmp_unsigned;
  594. /* we want (s->pcpu * pcpu_scale) to never overflow */
  595. while (pcpu_scale >= 1024) {
  596. pcpu_scale /= 4;
  597. pcpu_shift -= 2;
  598. }
  599. pcpu_half = (1U << pcpu_shift) / (ENABLE_FEATURE_TOP_DECIMALS ? 20 : 2);
  600. /* printf(" pmem_scale=%u pcpu_scale=%u ", pmem_scale, pcpu_scale); */
  601. #endif
  602. /* Ok, all preliminary data is ready, go through the list */
  603. scr_width += 2; /* account for leading '\n' and trailing NUL */
  604. if (lines_rem > ntop - G_scroll_ofs)
  605. lines_rem = ntop - G_scroll_ofs;
  606. s = top + G_scroll_ofs;
  607. while (--lines_rem >= 0) {
  608. unsigned col;
  609. CALC_STAT(pmem, (s->vsz*pmem_scale + pmem_half) >> pmem_shift);
  610. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  611. CALC_STAT(pcpu, (s->pcpu*pcpu_scale + pcpu_half) >> pcpu_shift);
  612. #endif
  613. if (s->vsz >= 100000)
  614. sprintf(vsz_str_buf, "%6ldm", s->vsz/1024);
  615. else
  616. sprintf(vsz_str_buf, "%7lu", s->vsz);
  617. /* PID PPID USER STAT VSZ %VSZ [%CPU] COMMAND */
  618. col = snprintf(line_buf, scr_width,
  619. "\n" "%5u%6u %-8.8s %s%s" FMT
  620. IF_FEATURE_TOP_SMP_PROCESS(" %3d")
  621. IF_FEATURE_TOP_CPU_USAGE_PERCENTAGE(FMT)
  622. " ",
  623. s->pid, s->ppid, get_cached_username(s->uid),
  624. s->state, vsz_str_buf,
  625. SHOW_STAT(pmem)
  626. IF_FEATURE_TOP_SMP_PROCESS(, s->last_seen_on_cpu)
  627. IF_FEATURE_TOP_CPU_USAGE_PERCENTAGE(, SHOW_STAT(pcpu))
  628. );
  629. if ((int)(col + 1) < scr_width)
  630. read_cmdline(line_buf + col, scr_width - col, s->pid, s->comm);
  631. fputs(line_buf, stdout);
  632. /* printf(" %d/%d %lld/%lld", s->pcpu, total_pcpu,
  633. cur_jif.busy - prev_jif.busy, cur_jif.total - prev_jif.total); */
  634. s++;
  635. }
  636. /* printf(" %d", hist_iterations); */
  637. bb_putchar(OPT_BATCH_MODE ? '\n' : '\r');
  638. fflush_all();
  639. }
  640. #undef UPSCALE
  641. #undef SHOW_STAT
  642. #undef CALC_STAT
  643. #undef FMT
  644. static void clearmems(void)
  645. {
  646. clear_username_cache();
  647. free(top);
  648. top = NULL;
  649. }
  650. #if ENABLE_FEATURE_USE_TERMIOS
  651. static void reset_term(void)
  652. {
  653. if (!OPT_BATCH_MODE)
  654. tcsetattr_stdin_TCSANOW(&initial_settings);
  655. if (ENABLE_FEATURE_CLEAN_UP) {
  656. clearmems();
  657. # if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  658. free(prev_hist);
  659. # endif
  660. }
  661. }
  662. static void sig_catcher(int sig)
  663. {
  664. reset_term();
  665. kill_myself_with_sig(sig);
  666. }
  667. #endif /* FEATURE_USE_TERMIOS */
  668. /*
  669. * TOPMEM support
  670. */
  671. typedef unsigned long mem_t;
  672. typedef struct topmem_status_t {
  673. unsigned pid;
  674. char comm[COMM_LEN];
  675. /* vsz doesn't count /dev/xxx mappings except /dev/zero */
  676. mem_t vsz ;
  677. mem_t vszrw ;
  678. mem_t rss ;
  679. mem_t rss_sh ;
  680. mem_t dirty ;
  681. mem_t dirty_sh;
  682. mem_t stack ;
  683. } topmem_status_t;
  684. enum { NUM_SORT_FIELD = 7 };
  685. #define topmem ((topmem_status_t*)top)
  686. #if ENABLE_FEATURE_TOPMEM
  687. static int topmem_sort(char *a, char *b)
  688. {
  689. int n;
  690. mem_t l, r;
  691. n = offsetof(topmem_status_t, vsz) + (sort_field * sizeof(mem_t));
  692. l = *(mem_t*)(a + n);
  693. r = *(mem_t*)(b + n);
  694. if (l == r) {
  695. l = ((topmem_status_t*)a)->dirty;
  696. r = ((topmem_status_t*)b)->dirty;
  697. }
  698. /* We want to avoid unsigned->signed and truncation errors */
  699. /* l>r: -1, l=r: 0, l<r: 1 */
  700. n = (l > r) ? -1 : (l != r);
  701. return inverted ? -n : n;
  702. }
  703. /* display header info (meminfo / loadavg) */
  704. static void display_topmem_header(int scr_width, int *lines_rem_p)
  705. {
  706. enum {
  707. TOTAL = 0, MFREE, BUF, CACHE,
  708. SWAPTOTAL, SWAPFREE, DIRTY,
  709. MWRITE, ANON, MAP, SLAB,
  710. NUM_FIELDS
  711. };
  712. static const char match[NUM_FIELDS][12] = {
  713. "\x09" "MemTotal:", // TOTAL
  714. "\x08" "MemFree:", // MFREE
  715. "\x08" "Buffers:", // BUF
  716. "\x07" "Cached:", // CACHE
  717. "\x0a" "SwapTotal:", // SWAPTOTAL
  718. "\x09" "SwapFree:", // SWAPFREE
  719. "\x06" "Dirty:", // DIRTY
  720. "\x0a" "Writeback:", // MWRITE
  721. "\x0a" "AnonPages:", // ANON
  722. "\x07" "Mapped:", // MAP
  723. "\x05" "Slab:", // SLAB
  724. };
  725. char meminfo_buf[4 * 1024];
  726. const char *Z[NUM_FIELDS];
  727. unsigned i;
  728. int sz;
  729. for (i = 0; i < NUM_FIELDS; i++)
  730. Z[i] = "?";
  731. /* read memory info */
  732. sz = open_read_close("meminfo", meminfo_buf, sizeof(meminfo_buf) - 1);
  733. if (sz >= 0) {
  734. char *p = meminfo_buf;
  735. meminfo_buf[sz] = '\0';
  736. /* Note that fields always appear in the match[] order */
  737. for (i = 0; i < NUM_FIELDS; i++) {
  738. char *found = strstr(p, match[i] + 1);
  739. if (found) {
  740. /* Cut "NNNN" out of " NNNN kb" */
  741. char *s = skip_whitespace(found + match[i][0]);
  742. p = skip_non_whitespace(s);
  743. *p++ = '\0';
  744. Z[i] = s;
  745. }
  746. }
  747. }
  748. snprintf(line_buf, LINE_BUF_SIZE,
  749. "Mem total:%s anon:%s map:%s free:%s",
  750. Z[TOTAL], Z[ANON], Z[MAP], Z[MFREE]);
  751. printf(OPT_BATCH_MODE ? "%.*s\n" : "\033[H\033[J%.*s\n", scr_width, line_buf);
  752. snprintf(line_buf, LINE_BUF_SIZE,
  753. " slab:%s buf:%s cache:%s dirty:%s write:%s",
  754. Z[SLAB], Z[BUF], Z[CACHE], Z[DIRTY], Z[MWRITE]);
  755. printf("%.*s\n", scr_width, line_buf);
  756. snprintf(line_buf, LINE_BUF_SIZE,
  757. "Swap total:%s free:%s", // TODO: % used?
  758. Z[SWAPTOTAL], Z[SWAPFREE]);
  759. printf("%.*s\n", scr_width, line_buf);
  760. (*lines_rem_p) -= 3;
  761. }
  762. static void ulltoa6_and_space(unsigned long long ul, char buf[6])
  763. {
  764. /* see http://en.wikipedia.org/wiki/Tera */
  765. smart_ulltoa5(ul, buf, " mgtpezy")[0] = ' ';
  766. }
  767. static NOINLINE void display_topmem_process_list(int lines_rem, int scr_width)
  768. {
  769. #define HDR_STR " PID VSZ VSZRW RSS (SHR) DIRTY (SHR) STACK"
  770. #define MIN_WIDTH sizeof(HDR_STR)
  771. const topmem_status_t *s = topmem + G_scroll_ofs;
  772. display_topmem_header(scr_width, &lines_rem);
  773. strcpy(line_buf, HDR_STR " COMMAND");
  774. line_buf[11 + sort_field * 6] = "^_"[inverted];
  775. printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width, line_buf);
  776. lines_rem--;
  777. if (lines_rem > ntop - G_scroll_ofs)
  778. lines_rem = ntop - G_scroll_ofs;
  779. while (--lines_rem >= 0) {
  780. /* PID VSZ VSZRW RSS (SHR) DIRTY (SHR) COMMAND */
  781. ulltoa6_and_space(s->pid , &line_buf[0*6]);
  782. ulltoa6_and_space(s->vsz , &line_buf[1*6]);
  783. ulltoa6_and_space(s->vszrw , &line_buf[2*6]);
  784. ulltoa6_and_space(s->rss , &line_buf[3*6]);
  785. ulltoa6_and_space(s->rss_sh , &line_buf[4*6]);
  786. ulltoa6_and_space(s->dirty , &line_buf[5*6]);
  787. ulltoa6_and_space(s->dirty_sh, &line_buf[6*6]);
  788. ulltoa6_and_space(s->stack , &line_buf[7*6]);
  789. line_buf[8*6] = '\0';
  790. if (scr_width > (int)MIN_WIDTH) {
  791. read_cmdline(&line_buf[8*6], scr_width - MIN_WIDTH, s->pid, s->comm);
  792. }
  793. printf("\n""%.*s", scr_width, line_buf);
  794. s++;
  795. }
  796. bb_putchar(OPT_BATCH_MODE ? '\n' : '\r');
  797. fflush_all();
  798. #undef HDR_STR
  799. #undef MIN_WIDTH
  800. }
  801. #else
  802. void display_topmem_process_list(int lines_rem, int scr_width);
  803. int topmem_sort(char *a, char *b);
  804. #endif /* TOPMEM */
  805. /*
  806. * end TOPMEM support
  807. */
  808. enum {
  809. TOP_MASK = 0
  810. | PSSCAN_PID
  811. | PSSCAN_PPID
  812. | PSSCAN_VSZ
  813. | PSSCAN_STIME
  814. | PSSCAN_UTIME
  815. | PSSCAN_STATE
  816. | PSSCAN_COMM
  817. | PSSCAN_CPU
  818. | PSSCAN_UIDGID,
  819. TOPMEM_MASK = 0
  820. | PSSCAN_PID
  821. | PSSCAN_SMAPS
  822. | PSSCAN_COMM,
  823. EXIT_MASK = (unsigned)-1,
  824. };
  825. #if ENABLE_FEATURE_USE_TERMIOS
  826. static unsigned handle_input(unsigned scan_mask, unsigned interval)
  827. {
  828. struct pollfd pfd[1];
  829. if (option_mask32 & OPT_EOF) {
  830. /* EOF on stdin ("top </dev/null") */
  831. sleep(interval);
  832. return scan_mask;
  833. }
  834. pfd[0].fd = 0;
  835. pfd[0].events = POLLIN;
  836. while (1) {
  837. int32_t c;
  838. c = read_key(STDIN_FILENO, G.kbd_input, interval * 1000);
  839. if (c == -1 && errno != EAGAIN) {
  840. /* error/EOF */
  841. option_mask32 |= OPT_EOF;
  842. break;
  843. }
  844. interval = 0;
  845. if (c == initial_settings.c_cc[VINTR])
  846. return EXIT_MASK;
  847. if (c == initial_settings.c_cc[VEOF])
  848. return EXIT_MASK;
  849. if (c == KEYCODE_UP) {
  850. G_scroll_ofs--;
  851. goto normalize_ofs;
  852. }
  853. if (c == KEYCODE_DOWN) {
  854. G_scroll_ofs++;
  855. goto normalize_ofs;
  856. }
  857. if (c == KEYCODE_HOME) {
  858. G_scroll_ofs = 0;
  859. break;
  860. }
  861. if (c == KEYCODE_END) {
  862. G_scroll_ofs = ntop - G.lines / 2;
  863. goto normalize_ofs;
  864. }
  865. if (c == KEYCODE_PAGEUP) {
  866. G_scroll_ofs -= G.lines / 2;
  867. goto normalize_ofs;
  868. }
  869. if (c == KEYCODE_PAGEDOWN) {
  870. G_scroll_ofs += G.lines / 2;
  871. normalize_ofs:
  872. if (G_scroll_ofs >= ntop)
  873. G_scroll_ofs = ntop - 1;
  874. if (G_scroll_ofs < 0)
  875. G_scroll_ofs = 0;
  876. break;
  877. }
  878. c |= 0x20; /* lowercase */
  879. if (c == 'q')
  880. return EXIT_MASK;
  881. if (c == 'n') {
  882. IF_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
  883. sort_function[0] = pid_sort;
  884. continue;
  885. }
  886. if (c == 'm') {
  887. IF_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
  888. sort_function[0] = mem_sort;
  889. # if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  890. sort_function[1] = pcpu_sort;
  891. sort_function[2] = time_sort;
  892. # endif
  893. continue;
  894. }
  895. # if ENABLE_FEATURE_SHOW_THREADS
  896. if (c == 'h'
  897. IF_FEATURE_TOPMEM(&& scan_mask != TOPMEM_MASK)
  898. ) {
  899. scan_mask ^= PSSCAN_TASKS;
  900. continue;
  901. }
  902. # endif
  903. # if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  904. if (c == 'p') {
  905. IF_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
  906. sort_function[0] = pcpu_sort;
  907. sort_function[1] = mem_sort;
  908. sort_function[2] = time_sort;
  909. continue;
  910. }
  911. if (c == 't') {
  912. IF_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
  913. sort_function[0] = time_sort;
  914. sort_function[1] = mem_sort;
  915. sort_function[2] = pcpu_sort;
  916. continue;
  917. }
  918. # if ENABLE_FEATURE_TOPMEM
  919. if (c == 's') {
  920. scan_mask = TOPMEM_MASK;
  921. free(prev_hist);
  922. prev_hist = NULL;
  923. prev_hist_count = 0;
  924. sort_field = (sort_field + 1) % NUM_SORT_FIELD;
  925. continue;
  926. }
  927. # endif
  928. if (c == 'r') {
  929. inverted ^= 1;
  930. continue;
  931. }
  932. # if ENABLE_FEATURE_TOP_SMP_CPU
  933. /* procps-2.0.18 uses 'C', 3.2.7 uses '1' */
  934. if (c == 'c' || c == '1') {
  935. /* User wants to toggle per cpu <> aggregate */
  936. if (smp_cpu_info) {
  937. free(cpu_prev_jif);
  938. free(cpu_jif);
  939. cpu_jif = &cur_jif;
  940. cpu_prev_jif = &prev_jif;
  941. } else {
  942. /* Prepare for xrealloc() */
  943. cpu_jif = cpu_prev_jif = NULL;
  944. }
  945. num_cpus = 0;
  946. smp_cpu_info = !smp_cpu_info;
  947. get_jiffy_counts();
  948. continue;
  949. }
  950. # endif
  951. # endif
  952. break; /* unknown key -> force refresh */
  953. }
  954. return scan_mask;
  955. }
  956. #endif
  957. //usage:#if ENABLE_FEATURE_SHOW_THREADS || ENABLE_FEATURE_TOP_SMP_CPU
  958. //usage:# define IF_SHOW_THREADS_OR_TOP_SMP(...) __VA_ARGS__
  959. //usage:#else
  960. //usage:# define IF_SHOW_THREADS_OR_TOP_SMP(...)
  961. //usage:#endif
  962. //usage:#define top_trivial_usage
  963. //usage: "[-b] [-nCOUNT] [-dSECONDS]" IF_FEATURE_TOPMEM(" [-m]")
  964. //usage:#define top_full_usage "\n\n"
  965. //usage: "Provide a view of process activity in real time."
  966. //usage: "\n""Read the status of all processes from /proc each SECONDS"
  967. //usage: "\n""and display a screenful of them."
  968. //usage: "\n""Keys:"
  969. //usage: "\n"" N/M"
  970. //usage: IF_FEATURE_TOP_CPU_USAGE_PERCENTAGE("/P")
  971. //usage: IF_FEATURE_TOP_CPU_USAGE_PERCENTAGE("/T")
  972. //usage: ": " IF_FEATURE_TOPMEM("show CPU usage, ") "sort by pid/mem"
  973. //usage: IF_FEATURE_TOP_CPU_USAGE_PERCENTAGE("/cpu")
  974. //usage: IF_FEATURE_TOP_CPU_USAGE_PERCENTAGE("/time")
  975. //usage: IF_FEATURE_TOPMEM(
  976. //usage: "\n"" S: show memory"
  977. //usage: )
  978. //usage: "\n"" R: reverse sort"
  979. //usage: IF_SHOW_THREADS_OR_TOP_SMP(
  980. //usage: "\n"" "
  981. //usage: IF_FEATURE_SHOW_THREADS("H: toggle threads")
  982. //usage: IF_FEATURE_SHOW_THREADS(IF_FEATURE_TOP_SMP_CPU(", "))
  983. //usage: IF_FEATURE_TOP_SMP_CPU("1: toggle SMP")
  984. //usage: )
  985. //usage: "\n"" Q,^C: exit"
  986. //usage: "\n"
  987. //usage: "\n""Options:"
  988. //usage: "\n"" -b Batch mode"
  989. //usage: "\n"" -n N Exit after N iterations"
  990. //usage: "\n"" -d N Delay between updates"
  991. //usage: IF_FEATURE_TOPMEM(
  992. //usage: "\n"" -m Same as 's' key"
  993. //usage: )
  994. /* Interactive testing:
  995. * echo sss | ./busybox top
  996. * - shows memory screen
  997. * echo sss | ./busybox top -bn1 >mem
  998. * - saves memory screen - the *whole* list, not first NROWS processes!
  999. * echo .m.s.s.s.s.s.s.q | ./busybox top -b >z
  1000. * - saves several different screens, and exits
  1001. *
  1002. * TODO: -i STRING param as a better alternative?
  1003. */
  1004. int top_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1005. int top_main(int argc UNUSED_PARAM, char **argv)
  1006. {
  1007. int iterations;
  1008. unsigned col;
  1009. unsigned interval;
  1010. char *str_interval, *str_iterations;
  1011. unsigned scan_mask = TOP_MASK;
  1012. #if ENABLE_FEATURE_USE_TERMIOS
  1013. struct termios new_settings;
  1014. #endif
  1015. INIT_G();
  1016. interval = 5; /* default update interval is 5 seconds */
  1017. iterations = 0; /* infinite */
  1018. #if ENABLE_FEATURE_TOP_SMP_CPU
  1019. /*num_cpus = 0;*/
  1020. /*smp_cpu_info = 0;*/ /* to start with show aggregate */
  1021. cpu_jif = &cur_jif;
  1022. cpu_prev_jif = &prev_jif;
  1023. #endif
  1024. /* all args are options; -n NUM */
  1025. opt_complementary = "-"; /* options can be specified w/o dash */
  1026. col = getopt32(argv, "d:n:b"IF_FEATURE_TOPMEM("m"), &str_interval, &str_iterations);
  1027. #if ENABLE_FEATURE_TOPMEM
  1028. if (col & OPT_m) /* -m (busybox specific) */
  1029. scan_mask = TOPMEM_MASK;
  1030. #endif
  1031. if (col & OPT_d) {
  1032. /* work around for "-d 1" -> "-d -1" done by getopt32
  1033. * (opt_complementary == "-" does this) */
  1034. if (str_interval[0] == '-')
  1035. str_interval++;
  1036. /* Need to limit it to not overflow poll timeout */
  1037. interval = xatou16(str_interval);
  1038. }
  1039. if (col & OPT_n) {
  1040. if (str_iterations[0] == '-')
  1041. str_iterations++;
  1042. iterations = xatou(str_iterations);
  1043. }
  1044. /* change to /proc */
  1045. xchdir("/proc");
  1046. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  1047. sort_function[0] = pcpu_sort;
  1048. sort_function[1] = mem_sort;
  1049. sort_function[2] = time_sort;
  1050. #else
  1051. sort_function[0] = mem_sort;
  1052. #endif
  1053. if (OPT_BATCH_MODE) {
  1054. option_mask32 |= OPT_EOF;
  1055. }
  1056. #if ENABLE_FEATURE_USE_TERMIOS
  1057. else {
  1058. tcgetattr(0, (void *) &initial_settings);
  1059. memcpy(&new_settings, &initial_settings, sizeof(new_settings));
  1060. /* unbuffered input, turn off echo */
  1061. new_settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHONL);
  1062. tcsetattr_stdin_TCSANOW(&new_settings);
  1063. }
  1064. bb_signals(BB_FATAL_SIGS, sig_catcher);
  1065. /* Eat initial input, if any */
  1066. scan_mask = handle_input(scan_mask, 0);
  1067. #endif
  1068. while (scan_mask != EXIT_MASK) {
  1069. procps_status_t *p = NULL;
  1070. if (OPT_BATCH_MODE) {
  1071. G.lines = INT_MAX;
  1072. col = LINE_BUF_SIZE - 2; /* +2 bytes for '\n', NUL */
  1073. } else {
  1074. G.lines = 24; /* default */
  1075. col = 79;
  1076. #if ENABLE_FEATURE_USE_TERMIOS
  1077. /* We output to stdout, we need size of stdout (not stdin)! */
  1078. get_terminal_width_height(STDOUT_FILENO, &col, &G.lines);
  1079. if (G.lines < 5 || col < 10) {
  1080. sleep(interval);
  1081. continue;
  1082. }
  1083. #endif
  1084. if (col > LINE_BUF_SIZE - 2)
  1085. col = LINE_BUF_SIZE - 2;
  1086. }
  1087. /* read process IDs & status for all the processes */
  1088. ntop = 0;
  1089. while ((p = procps_scan(p, scan_mask)) != NULL) {
  1090. int n;
  1091. #if ENABLE_FEATURE_TOPMEM
  1092. if (scan_mask != TOPMEM_MASK)
  1093. #endif
  1094. {
  1095. n = ntop;
  1096. top = xrealloc_vector(top, 6, ntop++);
  1097. top[n].pid = p->pid;
  1098. top[n].ppid = p->ppid;
  1099. top[n].vsz = p->vsz;
  1100. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  1101. top[n].ticks = p->stime + p->utime;
  1102. #endif
  1103. top[n].uid = p->uid;
  1104. strcpy(top[n].state, p->state);
  1105. strcpy(top[n].comm, p->comm);
  1106. #if ENABLE_FEATURE_TOP_SMP_PROCESS
  1107. top[n].last_seen_on_cpu = p->last_seen_on_cpu;
  1108. #endif
  1109. }
  1110. #if ENABLE_FEATURE_TOPMEM
  1111. else { /* TOPMEM */
  1112. if (!(p->smaps.mapped_ro | p->smaps.mapped_rw))
  1113. continue; /* kernel threads are ignored */
  1114. n = ntop;
  1115. /* No bug here - top and topmem are the same */
  1116. top = xrealloc_vector(topmem, 6, ntop++);
  1117. strcpy(topmem[n].comm, p->comm);
  1118. topmem[n].pid = p->pid;
  1119. topmem[n].vsz = p->smaps.mapped_rw + p->smaps.mapped_ro;
  1120. topmem[n].vszrw = p->smaps.mapped_rw;
  1121. topmem[n].rss_sh = p->smaps.shared_clean + p->smaps.shared_dirty;
  1122. topmem[n].rss = p->smaps.private_clean + p->smaps.private_dirty + topmem[n].rss_sh;
  1123. topmem[n].dirty = p->smaps.private_dirty + p->smaps.shared_dirty;
  1124. topmem[n].dirty_sh = p->smaps.shared_dirty;
  1125. topmem[n].stack = p->smaps.stack;
  1126. }
  1127. #endif
  1128. } /* end of "while we read /proc" */
  1129. if (ntop == 0) {
  1130. bb_error_msg("no process info in /proc");
  1131. break;
  1132. }
  1133. if (scan_mask != TOPMEM_MASK) {
  1134. #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
  1135. if (!prev_hist_count) {
  1136. do_stats();
  1137. usleep(100000);
  1138. clearmems();
  1139. continue;
  1140. }
  1141. do_stats();
  1142. /* TODO: we don't need to sort all 10000 processes, we need to find top 24! */
  1143. qsort(top, ntop, sizeof(top_status_t), (void*)mult_lvl_cmp);
  1144. #else
  1145. qsort(top, ntop, sizeof(top_status_t), (void*)(sort_function[0]));
  1146. #endif
  1147. }
  1148. #if ENABLE_FEATURE_TOPMEM
  1149. else { /* TOPMEM */
  1150. qsort(topmem, ntop, sizeof(topmem_status_t), (void*)topmem_sort);
  1151. }
  1152. #endif
  1153. if (scan_mask != TOPMEM_MASK)
  1154. display_process_list(G.lines, col);
  1155. #if ENABLE_FEATURE_TOPMEM
  1156. else
  1157. display_topmem_process_list(G.lines, col);
  1158. #endif
  1159. clearmems();
  1160. if (iterations >= 0 && !--iterations)
  1161. break;
  1162. #if !ENABLE_FEATURE_USE_TERMIOS
  1163. sleep(interval);
  1164. #else
  1165. scan_mask = handle_input(scan_mask, interval);
  1166. #endif /* FEATURE_USE_TERMIOS */
  1167. } /* end of "while (not Q)" */
  1168. bb_putchar('\n');
  1169. #if ENABLE_FEATURE_USE_TERMIOS
  1170. reset_term();
  1171. #endif
  1172. return EXIT_SUCCESS;
  1173. }