top.c 35 KB

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