3
0

top.c 33 KB

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