top.c 33 KB

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