87e85003d9d20adfe8c7407686152b789eedad11
[people/mcb30/busybox.git] / procps / top.c
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
21 /* Original code Copyrights */
22 /*
23  * Copyright (c) 1992 Branko Lankester
24  * Copyright (c) 1992 Roger Binns
25  * Copyright (C) 1994-1996 Charles L. Blake.
26  * Copyright (C) 1992-1998 Michael K. Johnson
27  * May be distributed under the conditions of the
28  * GNU Library General Public License
29  */
30
31 #include "libbb.h"
32
33
34 typedef struct top_status_t {
35         unsigned long vsz;
36 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
37         unsigned long ticks;
38         unsigned pcpu; /* delta of ticks */
39 #endif
40         unsigned pid, ppid;
41         unsigned uid;
42         char state[4];
43         char comm[COMM_LEN];
44 } top_status_t;
45
46 typedef struct jiffy_counts_t {
47         unsigned long long usr,nic,sys,idle,iowait,irq,softirq,steal;
48         unsigned long long total;
49         unsigned long long busy;
50 } jiffy_counts_t;
51
52 /* This structure stores some critical information from one frame to
53    the next. Used for finding deltas. */
54 typedef struct save_hist {
55         unsigned long ticks;
56         unsigned pid;
57 } save_hist;
58
59 typedef int (*cmp_funcp)(top_status_t *P, top_status_t *Q);
60
61 enum { SORT_DEPTH = 3 };
62
63 struct globals {
64         top_status_t *top;
65         int ntop;
66 #if ENABLE_FEATURE_USE_TERMIOS
67         struct termios initial_settings;
68 #endif
69 #if !ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
70         cmp_funcp sort_function[1];
71 #else
72         cmp_funcp sort_function[SORT_DEPTH];
73         struct save_hist *prev_hist;
74         int prev_hist_count;
75         jiffy_counts_t jif, prev_jif;
76         /* int hist_iterations; */
77         unsigned total_pcpu;
78         /* unsigned long total_vsz; */
79 #endif
80 };
81 #define G (*(struct globals*)&bb_common_bufsiz1)
82 #define top              (G.top               )
83 #define ntop             (G.ntop              )
84 #define initial_settings (G. initial_settings )
85 #define sort_function    (G.sort_function     )
86 #define prev_hist        (G.prev_hist         )
87 #define prev_hist_count  (G.prev_hist_count   )
88 #define jif              (G.jif               )
89 #define prev_jif         (G.prev_jif          )
90 #define total_pcpu       (G.total_pcpu        )
91
92
93 #define OPT_BATCH_MODE (option_mask32 & 0x4)
94
95
96 #if ENABLE_FEATURE_USE_TERMIOS
97 static int pid_sort(top_status_t *P, top_status_t *Q)
98 {
99         /* Buggy wrt pids with high bit set */
100         /* (linux pids are in [1..2^15-1]) */
101         return (Q->pid - P->pid);
102 }
103 #endif
104
105 static int mem_sort(top_status_t *P, top_status_t *Q)
106 {
107         /* We want to avoid unsigned->signed and truncation errors */
108         if (Q->vsz < P->vsz) return -1;
109         return Q->vsz != P->vsz; /* 0 if ==, 1 if > */
110 }
111
112
113 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
114
115 static int pcpu_sort(top_status_t *P, top_status_t *Q)
116 {
117         /* Buggy wrt ticks with high bit set */
118         /* Affects only processes for which ticks overflow */
119         return (int)Q->pcpu - (int)P->pcpu;
120 }
121
122 static int time_sort(top_status_t *P, top_status_t *Q)
123 {
124         /* We want to avoid unsigned->signed and truncation errors */
125         if (Q->ticks < P->ticks) return -1;
126         return Q->ticks != P->ticks; /* 0 if ==, 1 if > */
127 }
128
129 static int mult_lvl_cmp(void* a, void* b)
130 {
131         int i, cmp_val;
132
133         for (i = 0; i < SORT_DEPTH; i++) {
134                 cmp_val = (*sort_function[i])(a, b);
135                 if (cmp_val != 0)
136                         return cmp_val;
137         }
138         return 0;
139 }
140
141
142 static void get_jiffy_counts(void)
143 {
144         FILE* fp = xfopen("stat", "r");
145         prev_jif = jif;
146         if (fscanf(fp, "cpu  %lld %lld %lld %lld %lld %lld %lld %lld",
147                         &jif.usr,&jif.nic,&jif.sys,&jif.idle,
148                         &jif.iowait,&jif.irq,&jif.softirq,&jif.steal) < 4) {
149                 bb_error_msg_and_die("failed to read /proc/stat");
150         }
151         fclose(fp);
152         jif.total = jif.usr + jif.nic + jif.sys + jif.idle
153                         + jif.iowait + jif.irq + jif.softirq + jif.steal;
154         /* procps 2.x does not count iowait as busy time */
155         jif.busy = jif.total - jif.idle - jif.iowait;
156 }
157
158
159 static void do_stats(void)
160 {
161         top_status_t *cur;
162         pid_t pid;
163         int i, last_i, n;
164         struct save_hist *new_hist;
165
166         get_jiffy_counts();
167         total_pcpu = 0;
168         /* total_vsz = 0; */
169         new_hist = xmalloc(sizeof(struct save_hist)*ntop);
170         /*
171          * Make a pass through the data to get stats.
172          */
173         /* hist_iterations = 0; */
174         i = 0;
175         for (n = 0; n < ntop; n++) {
176                 cur = top + n;
177
178                 /*
179                  * Calculate time in cur process.  Time is sum of user time
180                  * and system time
181                  */
182                 pid = cur->pid;
183                 new_hist[n].ticks = cur->ticks;
184                 new_hist[n].pid = pid;
185
186                 /* find matching entry from previous pass */
187                 cur->pcpu = 0;
188                 /* do not start at index 0, continue at last used one
189                  * (brought hist_iterations from ~14000 down to 172) */
190                 last_i = i;
191                 if (prev_hist_count) do {
192                         if (prev_hist[i].pid == pid) {
193                                 cur->pcpu = cur->ticks - prev_hist[i].ticks;
194                                 total_pcpu += cur->pcpu;
195                                 break;
196                         }
197                         i = (i+1) % prev_hist_count;
198                         /* hist_iterations++; */
199                 } while (i != last_i);
200                 /* total_vsz += cur->vsz; */
201         }
202
203         /*
204          * Save cur frame's information.
205          */
206         free(prev_hist);
207         prev_hist = new_hist;
208         prev_hist_count = ntop;
209 }
210 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
211
212 #if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS && ENABLE_FEATURE_TOP_DECIMALS
213 /* formats 7 char string (8 with terminating NUL) */
214 static char *fmt_100percent_8(char pbuf[8], unsigned value, unsigned total)
215 {
216         unsigned t;
217         if (value >= total) { /* 100% ? */
218                 strcpy(pbuf, "  100% ");
219                 return pbuf;
220         }
221         /* else generate " [N/space]N.N% " string */
222         value = 1000 * value / total;
223         t = value / 100;
224         value = value % 100;
225         pbuf[0] = ' ';
226         pbuf[1] = t ? t + '0' : ' ';
227         pbuf[2] = '0' + (value / 10);
228         pbuf[3] = '.';
229         pbuf[4] = '0' + (value % 10);
230         pbuf[5] = '%';
231         pbuf[6] = ' ';
232         pbuf[7] = '\0';
233         return pbuf;
234 }
235 #endif
236
237 static unsigned long display_header(int scr_width)
238 {
239         FILE *fp;
240         char buf[80];
241         char scrbuf[80];
242         unsigned long total, used, mfree, shared, buffers, cached;
243 #if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS
244         unsigned total_diff;
245 #endif
246
247         /* read memory info */
248         fp = xfopen("meminfo", "r");
249
250         /*
251          * Old kernels (such as 2.4.x) had a nice summary of memory info that
252          * we could parse, however this is gone entirely in 2.6. Try parsing
253          * the old way first, and if that fails, parse each field manually.
254          *
255          * First, we read in the first line. Old kernels will have bogus
256          * strings we don't care about, whereas new kernels will start right
257          * out with MemTotal:
258          *                              -- PFM.
259          */
260         if (fscanf(fp, "MemTotal: %lu %s\n", &total, buf) != 2) {
261                 fgets(buf, sizeof(buf), fp);    /* skip first line */
262
263                 fscanf(fp, "Mem: %lu %lu %lu %lu %lu %lu",
264                         &total, &used, &mfree, &shared, &buffers, &cached);
265                 /* convert to kilobytes */
266                 used /= 1024;
267                 mfree /= 1024;
268                 shared /= 1024;
269                 buffers /= 1024;
270                 cached /= 1024;
271                 total /= 1024;
272         } else {
273                 /*
274                  * Revert to manual parsing, which incidentally already has the
275                  * sizes in kilobytes. This should be safe for both 2.4 and
276                  * 2.6.
277                  */
278
279                 fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
280
281                 /*
282                  * MemShared: is no longer present in 2.6. Report this as 0,
283                  * to maintain consistent behavior with normal procps.
284                  */
285                 if (fscanf(fp, "MemShared: %lu %s\n", &shared, buf) != 2)
286                         shared = 0;
287
288                 fscanf(fp, "Buffers: %lu %s\n", &buffers, buf);
289                 fscanf(fp, "Cached: %lu %s\n", &cached, buf);
290
291                 used = total - mfree;
292         }
293         fclose(fp);
294
295         /* output memory info */
296         if (scr_width > sizeof(scrbuf))
297                 scr_width = sizeof(scrbuf);
298         snprintf(scrbuf, scr_width,
299                 "Mem: %luK used, %luK free, %luK shrd, %luK buff, %luK cached",
300                 used, mfree, shared, buffers, cached);
301         /* clear screen & go to top */
302         printf(OPT_BATCH_MODE ? "%s\n" : "\e[H\e[J%s\n", scrbuf);
303
304 #if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS
305         /*
306          * xxx% = (jif.xxx - prev_jif.xxx) / (jif.total - prev_jif.total) * 100%
307          */
308         /* using (unsigned) casts to make operations cheaper */
309         total_diff = ((unsigned)(jif.total - prev_jif.total) ? : 1);
310 #if ENABLE_FEATURE_TOP_DECIMALS
311 /* Generated code is approx +0.3k */
312 #define CALC_STAT(xxx) char xxx[8]
313 #define SHOW_STAT(xxx) fmt_100percent_8(xxx, (unsigned)(jif.xxx - prev_jif.xxx), total_diff)
314 #define FMT "%s"
315 #else
316 #define CALC_STAT(xxx) unsigned xxx = 100 * (unsigned)(jif.xxx - prev_jif.xxx) / total_diff
317 #define SHOW_STAT(xxx) xxx
318 #define FMT "%4u%% "
319 #endif
320         { /* need block: CALC_STAT are declarations */
321                 CALC_STAT(usr);
322                 CALC_STAT(sys);
323                 CALC_STAT(nic);
324                 CALC_STAT(idle);
325                 CALC_STAT(iowait);
326                 CALC_STAT(irq);
327                 CALC_STAT(softirq);
328                 //CALC_STAT(steal);
329
330                 snprintf(scrbuf, scr_width,
331                         /* Barely fits in 79 chars when in "decimals" mode. */
332                         "CPU:"FMT"usr"FMT"sys"FMT"nice"FMT"idle"FMT"io"FMT"irq"FMT"softirq",
333                         SHOW_STAT(usr), SHOW_STAT(sys), SHOW_STAT(nic), SHOW_STAT(idle),
334                         SHOW_STAT(iowait), SHOW_STAT(irq), SHOW_STAT(softirq)
335                         //, SHOW_STAT(steal) - what is this 'steal' thing?
336                         // I doubt anyone wants to know it
337                 );
338         }
339         puts(scrbuf);
340 #undef SHOW_STAT
341 #undef CALC_STAT
342 #undef FMT
343 #endif
344
345         /* read load average as a string */
346         buf[0] = '\0';
347         open_read_close("loadavg", buf, sizeof("N.NN N.NN N.NN")-1);
348         buf[sizeof("N.NN N.NN N.NN")-1] = '\0';
349         snprintf(scrbuf, scr_width, "Load average: %s", buf);
350         puts(scrbuf);
351
352         return total;
353 }
354
355 static void display_process_list(int count, int scr_width)
356 {
357         enum {
358                 BITS_PER_INT = sizeof(int)*8
359         };
360
361         top_status_t *s = top;
362         char vsz_str_buf[8];
363         unsigned long total_memory = display_header(scr_width); /* or use total_vsz? */
364         /* xxx_shift and xxx_scale variables allow us to replace
365          * expensive divides with multiply and shift */
366         unsigned pmem_shift, pmem_scale, pmem_half;
367 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
368         unsigned pcpu_shift, pcpu_scale, pcpu_half;
369         unsigned busy_jifs;
370
371         /* what info of the processes is shown */
372         printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
373                 "  PID  PPID USER     STAT   VSZ %MEM %CPU COMMAND");
374 #define MIN_WIDTH \
375         sizeof( "  PID  PPID USER     STAT   VSZ %MEM %CPU C")
376 #else
377
378         /* !CPU_USAGE_PERCENTAGE */
379         printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
380                 "  PID  PPID USER     STAT   VSZ %MEM COMMAND");
381 #define MIN_WIDTH \
382         sizeof( "  PID  PPID USER     STAT   VSZ %MEM C")
383 #endif
384
385 #if ENABLE_FEATURE_TOP_DECIMALS
386 #define UPSCALE 1000
387 #define CALC_STAT(name, val) div_t name = div((val), 10)
388 #define SHOW_STAT(name) name.quot, '0'+name.rem
389 #define FMT "%3u.%c"
390 #else
391 #define UPSCALE 100
392 #define CALC_STAT(name, val) unsigned name = (val)
393 #define SHOW_STAT(name) name
394 #define FMT "%4u%%"
395 #endif
396         /*
397          * MEM% = s->vsz/MemTotal
398          */
399         pmem_shift = BITS_PER_INT-11;
400         pmem_scale = UPSCALE*(1U<<(BITS_PER_INT-11)) / total_memory;
401         /* s->vsz is in kb. we want (s->vsz * pmem_scale) to never overflow */
402         while (pmem_scale >= 512) {
403                 pmem_scale /= 4;
404                 pmem_shift -= 2;
405         }
406         pmem_half = (1U << pmem_shift) / (ENABLE_FEATURE_TOP_DECIMALS? 20 : 2);
407 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
408         busy_jifs = jif.busy - prev_jif.busy;
409         /* This happens if there were lots of short-lived processes
410          * between two top updates (e.g. compilation) */
411         if (total_pcpu < busy_jifs) total_pcpu = busy_jifs;
412
413         /*
414          * CPU% = s->pcpu/sum(s->pcpu) * busy_cpu_ticks/total_cpu_ticks
415          * (pcpu is delta of sys+user time between samples)
416          */
417         /* (jif.xxx - prev_jif.xxx) and s->pcpu are
418          * in 0..~64000 range (HZ*update_interval).
419          * we assume that unsigned is at least 32-bit.
420          */
421         pcpu_shift = 6;
422         pcpu_scale = (UPSCALE*64*(uint16_t)busy_jifs ? : 1);
423         while (pcpu_scale < (1U<<(BITS_PER_INT-2))) {
424                 pcpu_scale *= 4;
425                 pcpu_shift += 2;
426         }
427         pcpu_scale /= ( (uint16_t)(jif.total-prev_jif.total)*total_pcpu ? : 1);
428         /* we want (s->pcpu * pcpu_scale) to never overflow */
429         while (pcpu_scale >= 1024) {
430                 pcpu_scale /= 4;
431                 pcpu_shift -= 2;
432         }
433         pcpu_half = (1U << pcpu_shift) / (ENABLE_FEATURE_TOP_DECIMALS? 20 : 2);
434         /* printf(" pmem_scale=%u pcpu_scale=%u ", pmem_scale, pcpu_scale); */
435 #endif
436
437         /* Ok, all prelim data is ready, go thru the list */
438         while (count-- > 0) {
439                 int col = scr_width;
440                 CALC_STAT(pmem, (s->vsz*pmem_scale + pmem_half) >> pmem_shift);
441 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
442                 CALC_STAT(pcpu, (s->pcpu*pcpu_scale + pcpu_half) >> pcpu_shift);
443 #endif
444
445                 if (s->vsz >= 100*1024)
446                         sprintf(vsz_str_buf, "%6ldm", s->vsz/1024);
447                 else
448                         sprintf(vsz_str_buf, "%7ld", s->vsz);
449                 // PID PPID USER STAT VSZ %MEM [%CPU] COMMAND
450                 col -= printf("\n" "%5u%6u %-8.8s %s%s" FMT
451 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
452                                 FMT
453 #endif
454                                 " ",
455                                 s->pid, s->ppid, get_cached_username(s->uid),
456                                 s->state, vsz_str_buf,
457                                 SHOW_STAT(pmem)
458 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
459                                 , SHOW_STAT(pcpu)
460 #endif
461                 );
462                 if (col > 0) {
463                         char buf[col + 1];
464                         read_cmdline(buf, col, s->pid, s->comm);
465                         fputs(buf, stdout);
466                 }
467                 /* printf(" %d/%d %lld/%lld", s->pcpu, total_pcpu,
468                         jif.busy - prev_jif.busy, jif.total - prev_jif.total); */
469                 s++;
470         }
471         /* printf(" %d", hist_iterations); */
472         putchar(OPT_BATCH_MODE ? '\n' : '\r');
473         fflush(stdout);
474 }
475 #undef UPSCALE
476 #undef SHOW_STAT
477 #undef CALC_STAT
478 #undef FMT
479
480 static void clearmems(void)
481 {
482         clear_username_cache();
483         free(top);
484         top = 0;
485         ntop = 0;
486 }
487
488 #if ENABLE_FEATURE_USE_TERMIOS
489 #include <termios.h>
490 #include <signal.h>
491
492 static void reset_term(void)
493 {
494         tcsetattr(0, TCSANOW, (void *) &initial_settings);
495         if (ENABLE_FEATURE_CLEAN_UP) {
496                 clearmems();
497 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
498                 free(prev_hist);
499 #endif
500         }
501 }
502
503 static void sig_catcher(int sig ATTRIBUTE_UNUSED)
504 {
505         reset_term();
506         exit(1);
507 }
508 #endif /* FEATURE_USE_TERMIOS */
509
510
511 int top_main(int argc, char **argv);
512 int top_main(int argc, char **argv)
513 {
514         int count, lines, col;
515         unsigned interval;
516         int iterations = -1; /* infinite */
517         char *sinterval, *siterations;
518 #if ENABLE_FEATURE_USE_TERMIOS
519         struct termios new_settings;
520         struct pollfd pfd[1];
521         unsigned char c;
522
523         pfd[0].fd = 0;
524         pfd[0].events = POLLIN;
525 #endif /* FEATURE_USE_TERMIOS */
526
527         interval = 5; /* default update rate is 5 seconds */
528
529         /* do normal option parsing */
530         opt_complementary = "-";
531         getopt32(argv, "d:n:b", &sinterval, &siterations);
532         if (option_mask32 & 0x1) {
533                 /* Need to limit it to not overflow poll timeout */
534                 interval = xatou16(sinterval); // -d
535         }
536         if (option_mask32 & 0x2)
537                 iterations = xatoi_u(siterations); // -n
538         //if (option_mask32 & 0x4) // -b
539
540         /* change to /proc */
541         xchdir("/proc");
542 #if ENABLE_FEATURE_USE_TERMIOS
543         tcgetattr(0, (void *) &initial_settings);
544         memcpy(&new_settings, &initial_settings, sizeof(new_settings));
545         /* unbuffered input, turn off echo */
546         new_settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHONL);
547
548         signal(SIGTERM, sig_catcher);
549         signal(SIGINT, sig_catcher);
550         tcsetattr(0, TCSANOW, (void *) &new_settings);
551         atexit(reset_term);
552 #endif /* FEATURE_USE_TERMIOS */
553
554 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
555         sort_function[0] = pcpu_sort;
556         sort_function[1] = mem_sort;
557         sort_function[2] = time_sort;
558 #else
559         sort_function[0] = mem_sort;
560 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
561
562         while (1) {
563                 procps_status_t *p = NULL;
564
565                 /* Default */
566                 lines = 24 - 3 USE_FEATURE_TOP_CPU_GLOBAL_PERCENTS( - 1);
567                 col = 79;
568 #if ENABLE_FEATURE_USE_TERMIOS
569                 get_terminal_width_height(0, &col, &lines);
570                 /* We wrap horribly if width is too narrow (TODO) */
571                 if (lines < 5 || col < MIN_WIDTH) {
572                         sleep(interval);
573                         continue;
574                 }
575                 lines -= 3 USE_FEATURE_TOP_CPU_GLOBAL_PERCENTS( + 1);
576 #endif /* FEATURE_USE_TERMIOS */
577
578                 /* read process IDs & status for all the processes */
579                 while ((p = procps_scan(p, 0
580                                 | PSSCAN_PID
581                                 | PSSCAN_PPID
582                                 | PSSCAN_VSZ
583                                 | PSSCAN_STIME
584                                 | PSSCAN_UTIME
585                                 | PSSCAN_STATE
586                                 | PSSCAN_COMM
587                                 | PSSCAN_UIDGID
588                 )) != NULL) {
589                         int n = ntop;
590                         top = xrealloc(top, (++ntop) * sizeof(*top));
591                         top[n].pid = p->pid;
592                         top[n].ppid = p->ppid;
593                         top[n].vsz = p->vsz;
594 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
595                         top[n].ticks = p->stime + p->utime;
596 #endif
597                         top[n].uid = p->uid;
598                         strcpy(top[n].state, p->state);
599                         strcpy(top[n].comm, p->comm);
600                 }
601                 if (ntop == 0) {
602                         bb_error_msg_and_die("no process info in /proc");
603                 }
604 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
605                 if (!prev_hist_count) {
606                         do_stats();
607                         sleep(1);
608                         clearmems();
609                         continue;
610                 }
611                 do_stats();
612 /* TODO: we don't need to sort all 10000 processes, we need to find top 24! */
613                 qsort(top, ntop, sizeof(top_status_t), (void*)mult_lvl_cmp);
614 #else
615                 qsort(top, ntop, sizeof(top_status_t), (void*)(sort_function[0]));
616 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
617                 count = lines;
618                 if (OPT_BATCH_MODE || count > ntop) {
619                         count = ntop;
620                 }
621                 display_process_list(count, col);
622                 clearmems();
623                 if (iterations >= 0 && !--iterations)
624                         break;
625 #if !ENABLE_FEATURE_USE_TERMIOS
626                 sleep(interval);
627 #else
628                 if (poll(pfd, 1, interval * 1000) != 0) {
629                         if (read(0, &c, 1) != 1)    /* signal */
630                                 break;
631                         if (c == 'q' || c == initial_settings.c_cc[VINTR])
632                                 break;
633                         if (c == 'N')
634                                 sort_function[0] = pid_sort;
635                         if (c == 'M') {
636                                 sort_function[0] = mem_sort;
637 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
638                                 sort_function[1] = pcpu_sort;
639                                 sort_function[2] = time_sort;
640 #endif
641                         }
642 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
643                         if (c == 'P') {
644                                 sort_function[0] = pcpu_sort;
645                                 sort_function[1] = mem_sort;
646                                 sort_function[2] = time_sort;
647                         }
648                         if (c == 'T') {
649                                 sort_function[0] = time_sort;
650                                 sort_function[1] = mem_sort;
651                                 sort_function[2] = pcpu_sort;
652                         }
653 #endif
654                 }
655 #endif /* FEATURE_USE_TERMIOS */
656         }
657         putchar('\n');
658         return EXIT_SUCCESS;
659 }