From 08a72209c9b5cb74d851ef5c3db8c16eee6f657d Mon Sep 17 00:00:00 2001 From: Eric Andersen Date: Mon, 30 Sep 2002 20:52:10 +0000 Subject: [PATCH] last_patch58 from vodz: Ok. I generate patch for include to busybox-devel my work with top (original author give me maintaining) and telnetd (my support and unofficial maintaining) applets. Docs changes also: added awk, netstat, time applets to list ;) --- AUTHORS | 3 +- docs/busybox_footer.pod | 5 +- docs/busybox_header.pod | 28 +- include/applets.h | 3 + include/usage.h | 8 + networking/Makefile.in | 1 + networking/config.in | 1 + networking/telnetd.c | 538 ++++++++++++++++++++++++ procps/top.c | 875 ++++++++++++++++++++++++++-------------- 9 files changed, 1153 insertions(+), 309 deletions(-) create mode 100644 networking/telnetd.c diff --git a/AUTHORS b/AUTHORS index 47d450248..854ee12d8 100644 --- a/AUTHORS +++ b/AUTHORS @@ -55,7 +55,8 @@ Glenn McGrath ar, dpkg, dpkg-deb Vladimir Oleynik - cmdedit; ports: ash, stty, traceroute; locale, various fixes + cmdedit; ports: ash, stty, traceroute, telnetd, top; + locale, various fixes and irreconcilable critic of everything not perfect. Bruce Perens diff --git a/docs/busybox_footer.pod b/docs/busybox_footer.pod index 7c02003fc..b3de7e536 100644 --- a/docs/busybox_footer.pod +++ b/docs/busybox_footer.pod @@ -113,7 +113,8 @@ Glenn McGrath Vladimir Oleynik - cmdedit; ports: ash, stty, traceroute; locale, various fixes + cmdedit; ports: ash, stty, traceroute, telnetd, top; + locale, various fixes and irreconcilable critic of everything not perfect. =for html
@@ -166,4 +167,4 @@ Enrique Zanardi =cut -# $Id: busybox_footer.pod,v 1.5 2001/12/18 14:06:01 andersen Exp $ +# $Id: busybox_footer.pod,v 1.6 2002/09/30 20:52:08 andersen Exp $ diff --git a/docs/busybox_header.pod b/docs/busybox_header.pod index 0ea7dbfe7..517be81a3 100644 --- a/docs/busybox_header.pod +++ b/docs/busybox_header.pod @@ -55,20 +55,20 @@ terse runtime description of their behavior. Currently defined functions include: - addgroup, adduser, adjtimex, ar, basename, busybox, cat, chgrp, chmod, -chown, chroot, chvt, clear, cmp, cp, cpio, cut, date, dc, dd, deallocvt, -deluser, df, dirname, dmesg, dos2unix, dpkg, dpkg-deb, du, dumpkmap, dutmp, -echo, expr, false, fbset, fdflush, find, free, freeramdisk, fsck.minix, -getopt, getty, grep, gunzip, gzip, halt, head, hostid, hostname, id, -ifconfig, init, insmod, kill, killall, klogd, length, ln, loadacm, -loadfont, loadkmap, logger, logname, ls, lsmod, makedevs, md5sum, mkdir, -mkfifo, mkfs.minix, mknod, mkswap, mktemp, more, mount, mt, mv, nc, -nslookup, ping, pivot_root, poweroff, printf, ps, pwd, rdate, readlink, -reboot, renice, reset, rm, rmdir, rmmod, route, rpm2cpio, sed, setkeycodes, -sh, sleep, sort, stty, swapoff, swapon, sync, syslogd, tail, tar, tee, -telnet, test, tftp, touch, tr, true, tty, umount, uname, uniq, unix2dos, -update, uptime, usleep, uudecode, uuencode, watchdog, wc, wget, which, -whoami, xargs, yes, zcat, [ + addgroup, adduser, adjtimex, ar, awk, basename, busybox, cat, chgrp, +chmod, chown, chroot, chvt, clear, cmp, cp, cpio, cut, date, dc, dd, +deallocvt, deluser, df, dirname, dmesg, dos2unix, dpkg, dpkg-deb, du, +dumpkmap, dutmp, echo, expr, false, fbset, fdflush, find, free, +freeramdisk, fsck.minix, getopt, getty, grep, gunzip, gzip, halt, head, +hostid, hostname, id, ifconfig, init, insmod, kill, killall, klogd, length, +ln, loadacm, loadfont, loadkmap, logger, logname, ls, lsmod, makedevs, +md5sum, mkdir, mkfifo, mkfs.minix, mknod, mkswap, mktemp, more, mount, mt, +mv, nc, netstat, nslookup, ping, pivot_root, poweroff, printf, ps, pwd, +rdate, readlink, reboot, renice, reset, rm, rmdir, rmmod, route, rpm2cpio, +sed, setkeycodes, sh, sleep, sort, stty, swapoff, swapon, sync, syslogd, +tail, tar, tee, telnet, telnetd, test, tftp, time, top, touch, tr, true, +tty, umount, uname, uniq, unix2dos, update, uptime, usleep, uudecode, +uuencode, watchdog, wc, wget, which, whoami, xargs, yes, zcat, [ =over 4 diff --git a/include/applets.h b/include/applets.h index 9508c3a4b..60928aef2 100644 --- a/include/applets.h +++ b/include/applets.h @@ -464,6 +464,9 @@ #ifdef CONFIG_TELNET APPLET(telnet, telnet_main, _BB_DIR_USR_BIN, _BB_SUID_NEVER) #endif +#ifdef CONFIG_TELNETD + APPLET(telnetd, telnetd_main, _BB_DIR_USR_SBIN, _BB_SUID_NEVER) +#endif #ifdef CONFIG_TEST APPLET(test, test_main, _BB_DIR_USR_BIN, _BB_SUID_NEVER) #endif diff --git a/include/usage.h b/include/usage.h index 33a81c467..1e0fe6805 100644 --- a/include/usage.h +++ b/include/usage.h @@ -1801,6 +1801,14 @@ "Telnet is used to establish interactive communication with another\n"\ "computer over a network using the TELNET protocol." +#define telnetd_trivial_usage \ + "[OPTION]" +#define telnetd_full_usage \ + "Telnetd listens for incoming TELNET connections on PORT.\n"\ + "Options:\n" \ + "\t-p PORT\tlisten for connections on PORT (default 23)\n"\ + "\t-l LOGIN\texec LOGIN on connect (default /bin/sh)" + #define test_trivial_usage \ "EXPRESSION\n or [ EXPRESSION ]" #define test_full_usage \ diff --git a/networking/Makefile.in b/networking/Makefile.in index 425b5d3d9..510c8119d 100644 --- a/networking/Makefile.in +++ b/networking/Makefile.in @@ -32,6 +32,7 @@ NETWORKING-$(CONFIG_PING) += ping.o NETWORKING-$(CONFIG_PING6) += ping6.o NETWORKING-$(CONFIG_ROUTE) += route.o NETWORKING-$(CONFIG_TELNET) += telnet.o +NETWORKING-$(CONFIG_TELNETD) += telnetd.o NETWORKING-$(CONFIG_TFTP) += tftp.o NETWORKING-$(CONFIG_TRACEROUTE) += traceroute.o NETWORKING-$(CONFIG_UDHCPC) += udhcpc.o diff --git a/networking/config.in b/networking/config.in index bc11d83a7..4438a8c6c 100644 --- a/networking/config.in +++ b/networking/config.in @@ -34,6 +34,7 @@ bool 'telnet' CONFIG_TELNET if [ "$CONFIG_TELNET" = "y" ]; then bool ' Pass TERM type to remote host' CONFIG_FEATURE_TELNET_TTYPE fi +bool 'telnetd' CONFIG_TELNETD bool 'tftp' CONFIG_TFTP if [ "$CONFIG_TFTP" = "y" ]; then bool ' Enable "get" command' CONFIG_FEATURE_TFTP_GET diff --git a/networking/telnetd.c b/networking/telnetd.c new file mode 100644 index 000000000..edc018a2a --- /dev/null +++ b/networking/telnetd.c @@ -0,0 +1,538 @@ +/* $Id: telnetd.c,v 1.1 2002/09/30 20:52:04 andersen Exp $ + * + * Simple telnet server + * Bjorn Wesen, Axis Communications AB (bjornw@axis.com) + * + * This file is distributed under the Gnu Public License (GPL), + * please see the file LICENSE for further information. + * + * --------------------------------------------------------------------------- + * (C) Copyright 2000, Axis Communications AB, LUND, SWEDEN + **************************************************************************** + * + * The telnetd manpage says it all: + * + * Telnetd operates by allocating a pseudo-terminal device (see pty(4)) for + * a client, then creating a login process which has the slave side of the + * pseudo-terminal as stdin, stdout, and stderr. Telnetd manipulates the + * master side of the pseudo-terminal, implementing the telnet protocol and + * passing characters between the remote client and the login process. + * + * Vladimir Oleynik 2001 + * Set process group corrections, initial busybox port + */ + +/*#define DEBUG 1 */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef DEBUG +#define TELCMDS +#define TELOPTS +#endif +#include +#include +#include + +#include "busybox.h" + +#define BUFSIZE 4000 + +static const char *loginpath = "/bin/sh"; + +/* shell name and arguments */ + +static const char *argv_init[] = {NULL, NULL}; + +/* structure that describes a session */ + +struct tsession { + struct tsession *next; + int sockfd, ptyfd; + int shell_pid; + /* two circular buffers */ + char *buf1, *buf2; + int rdidx1, wridx1, size1; + int rdidx2, wridx2, size2; +}; + +/* + + This is how the buffers are used. The arrows indicate the movement + of data. + + +-------+ wridx1++ +------+ rdidx1++ +----------+ + | | <-------------- | buf1 | <-------------- | | + | | size1-- +------+ size1++ | | + | pty | | socket | + | | rdidx2++ +------+ wridx2++ | | + | | --------------> | buf2 | --------------> | | + +-------+ size2++ +------+ size2-- +----------+ + + Each session has got two buffers. + +*/ + +static int maxfd; + +static struct tsession *sessions; + + +/* + + Remove all IAC's from the buffer pointed to by bf (recieved IACs are ignored + and must be removed so as to not be interpreted by the terminal). Make an + uninterrupted string of characters fit for the terminal. Do this by packing + all characters meant for the terminal sequentially towards the end of bf. + + Return a pointer to the beginning of the characters meant for the terminal. + and make *num_totty the number of characters that should be sent to + the terminal. + + Note - If an IAC (3 byte quantity) starts before (bf + len) but extends + past (bf + len) then that IAC will be left unprocessed and *processed will be + less than len. + + FIXME - if we mean to send 0xFF to the terminal then it will be escaped, + what is the escape character? We aren't handling that situation here. + + */ +static char * +remove_iacs(struct tsession *ts, int *pnum_totty) { + unsigned char *ptr0 = ts->buf1 + ts->wridx1; + unsigned char *ptr = ptr0; + unsigned char *totty = ptr; + unsigned char *end = ptr + MIN(BUFSIZE - ts->wridx1, ts->size1); + int processed; + int num_totty; + + while (ptr < end) { + if (*ptr != IAC) { + *totty++ = *ptr++; + } + else { + if ((ptr+2) < end) { + /* the entire IAC is contained in the buffer + we were asked to process. */ +#ifdef DEBUG + fprintf(stderr, "Ignoring IAC %s,%s\n", + *ptr, TELCMD(*(ptr+1)), TELOPT(*(ptr+2))); +#endif + ptr += 3; + } else { + /* only the beginning of the IAC is in the + buffer we were asked to process, we can't + process this char. */ + break; + } + } + } + + processed = ptr - ptr0; + num_totty = totty - ptr0; + /* the difference between processed and num_to tty + is all the iacs we removed from the stream. + Adjust buf1 accordingly. */ + ts->wridx1 += processed - num_totty; + ts->size1 -= processed - num_totty; + *pnum_totty = num_totty; + /* move the chars meant for the terminal towards the end of the + buffer. */ + return memmove(ptr - num_totty, ptr0, num_totty); +} + + +static int +getpty(char *line) +{ + int p; +#ifdef HAVE_DEVPTS_FS + p = open("/dev/ptmx", 2); + if (p > 0) { + grantpt(p); + unlockpt(p); + strcpy(line, ptsname(p)); + return(p); + } +#else + struct stat stb; + int i; + int j; + + strcpy(line, "/dev/ptyXX"); + + for (i = 0; i < 16; i++) { + line[8] = "pqrstuvwxyzabcde"[i]; + line[9] = '0'; + if (stat(line, &stb) < 0) { + continue; + } + for (j = 0; j < 16; j++) { + line[9] = j < 10 ? j + '0' : j - 10 + 'a'; + if ((p = open(line, O_RDWR | O_NOCTTY)) >= 0) { + line[5] = 't'; + return p; + } + } + } +#endif /* HAVE_DEVPTS_FS */ + return -1; +} + + +static void +send_iac(struct tsession *ts, unsigned char command, int option) +{ + /* We rely on that there is space in the buffer for now. */ + char *b = ts->buf2 + ts->rdidx2; + *b++ = IAC; + *b++ = command; + *b++ = option; + ts->rdidx2 += 3; + ts->size2 += 3; +} + + +static struct tsession * +make_new_session(int sockfd) +{ + struct termios termbuf; + int pty, pid; + char tty_name[32]; + struct tsession *ts = malloc(sizeof(struct tsession) + BUFSIZE * 2); + + ts->buf1 = (char *)(&ts[1]); + ts->buf2 = ts->buf1 + BUFSIZE; + + ts->sockfd = sockfd; + + ts->rdidx1 = ts->wridx1 = ts->size1 = 0; + ts->rdidx2 = ts->wridx2 = ts->size2 = 0; + + /* Got a new connection, set up a tty and spawn a shell. */ + + pty = getpty(tty_name); + + if (pty < 0) { + syslog_msg(LOG_USER, LOG_ERR, "All network ports in use!"); + return 0; + } + + if (pty > maxfd) + maxfd = pty; + + ts->ptyfd = pty; + + /* Make the telnet client understand we will echo characters so it + * should not do it locally. We don't tell the client to run linemode, + * because we want to handle line editing and tab completion and other + * stuff that requires char-by-char support. + */ + + send_iac(ts, DO, TELOPT_ECHO); + send_iac(ts, DO, TELOPT_LFLOW); + send_iac(ts, WILL, TELOPT_ECHO); + send_iac(ts, WILL, TELOPT_SGA); + + + if ((pid = fork()) < 0) { + syslog_msg(LOG_USER, LOG_ERR, "Can`t forking"); + } + if (pid == 0) { + /* In child, open the child's side of the tty. */ + int i; + + for(i = 0; i <= maxfd; i++) + close(i); + /* make new process group */ + setsid(); + + if (open(tty_name, O_RDWR /*| O_NOCTTY*/) < 0) { + syslog_msg(LOG_USER, LOG_ERR, "Could not open tty"); + exit(1); + } + dup(0); + dup(0); + + tcsetpgrp(0, getpid()); + + /* The pseudo-terminal allocated to the client is configured to operate in + * cooked mode, and with XTABS CRMOD enabled (see tty(4)). + */ + + tcgetattr(0, &termbuf); + termbuf.c_lflag |= ECHO; /* if we use readline we dont want this */ + termbuf.c_oflag |= ONLCR|XTABS; + termbuf.c_iflag |= ICRNL; + termbuf.c_iflag &= ~IXOFF; + /*termbuf.c_lflag &= ~ICANON;*/ + tcsetattr(0, TCSANOW, &termbuf); + + /* exec shell, with correct argv and env */ + execv(loginpath, (char *const *)argv_init); + + /* NOT REACHED */ + syslog_msg(LOG_USER, LOG_ERR, "execv error"); + exit(1); + } + + ts->shell_pid = pid; + + return ts; +} + +static void +free_session(struct tsession *ts) +{ + struct tsession *t = sessions; + + /* Unlink this telnet session from the session list. */ + if(t == ts) + sessions = ts->next; + else { + while(t->next != ts) + t = t->next; + t->next = ts->next; + } + + kill(ts->shell_pid, SIGKILL); + + wait4(ts->shell_pid, NULL, 0, NULL); + + close(ts->ptyfd); + close(ts->sockfd); + + if(ts->ptyfd == maxfd || ts->sockfd == maxfd) + maxfd--; + if(ts->ptyfd == maxfd || ts->sockfd == maxfd) + maxfd--; + + free(ts); +} + +int +telnetd_main(int argc, char **argv) +{ + struct sockaddr_in sa; + int master_fd; + fd_set rdfdset, wrfdset; + int selret; + int on = 1; + int portnbr = 23; + int c; + + /* check if user supplied a port number */ + + for (;;) { + c = getopt( argc, argv, "p:l:"); + if (c == EOF) break; + switch (c) { + case 'p': + portnbr = atoi(optarg); + break; + case 'l': + loginpath = strdup (optarg); + break; + default: + show_usage(); + } + } + + if (access(loginpath, X_OK) < 0) { + error_msg_and_die ("'%s' unavailable.", loginpath); + } + + argv_init[0] = loginpath; + sessions = 0; + + /* Grab a TCP socket. */ + + master_fd = socket(AF_INET, SOCK_STREAM, 0); + if (master_fd < 0) { + perror_msg_and_die("socket"); + } + (void)setsockopt(master_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); + + /* Set it to listen to specified port. */ + + memset((void *)&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_port = htons(portnbr); + + if (bind(master_fd, (struct sockaddr *) &sa, sizeof(sa)) < 0) { + perror_msg_and_die("bind"); + } + + if (listen(master_fd, 1) < 0) { + perror_msg_and_die("listen"); + } + + if (daemon(0, 0) < 0) + perror_msg_and_die("daemon"); + + + maxfd = master_fd; + + do { + struct tsession *ts; + + FD_ZERO(&rdfdset); + FD_ZERO(&wrfdset); + + /* select on the master socket, all telnet sockets and their + * ptys if there is room in their respective session buffers. + */ + + FD_SET(master_fd, &rdfdset); + + ts = sessions; + while (ts) { + /* buf1 is used from socket to pty + * buf2 is used from pty to socket + */ + if (ts->size1 > 0) { + FD_SET(ts->ptyfd, &wrfdset); /* can write to pty */ + } + if (ts->size1 < BUFSIZE) { + FD_SET(ts->sockfd, &rdfdset); /* can read from socket */ + } + if (ts->size2 > 0) { + FD_SET(ts->sockfd, &wrfdset); /* can write to socket */ + } + if (ts->size2 < BUFSIZE) { + FD_SET(ts->ptyfd, &rdfdset); /* can read from pty */ + } + ts = ts->next; + } + + selret = select(maxfd + 1, &rdfdset, &wrfdset, 0, 0); + + if (!selret) + break; + + /* First check for and accept new sessions. */ + if (FD_ISSET(master_fd, &rdfdset)) { + int fd, salen; + + salen = sizeof(sa); + if ((fd = accept(master_fd, (struct sockaddr *)&sa, + &salen)) < 0) { + continue; + } else { + /* Create a new session and link it into + our active list. */ + struct tsession *new_ts = make_new_session(fd); + if (new_ts) { + new_ts->next = sessions; + sessions = new_ts; + if (fd > maxfd) + maxfd = fd; + } else { + close(fd); + } + } + } + + /* Then check for data tunneling. */ + + ts = sessions; + while (ts) { /* For all sessions... */ + int maxlen, w, r; + struct tsession *next = ts->next; /* in case we free ts. */ + + if (ts->size1 && FD_ISSET(ts->ptyfd, &wrfdset)) { + int num_totty; + char *ptr; + /* Write to pty from buffer 1. */ + + ptr = remove_iacs(ts, &num_totty); + + w = write(ts->ptyfd, ptr, num_totty); + if (w < 0) { + free_session(ts); + ts = next; + continue; + } + ts->wridx1 += w; + ts->size1 -= w; + if (ts->wridx1 == BUFSIZE) + ts->wridx1 = 0; + } + + if (ts->size2 && FD_ISSET(ts->sockfd, &wrfdset)) { + /* Write to socket from buffer 2. */ + maxlen = MIN(BUFSIZE - ts->wridx2, ts->size2); + w = write(ts->sockfd, ts->buf2 + ts->wridx2, maxlen); + if (w < 0) { + free_session(ts); + ts = next; + continue; + } + ts->wridx2 += w; + ts->size2 -= w; + if (ts->wridx2 == BUFSIZE) + ts->wridx2 = 0; + } + + if (ts->size1 < BUFSIZE && FD_ISSET(ts->sockfd, &rdfdset)) { + /* Read from socket to buffer 1. */ + maxlen = MIN(BUFSIZE - ts->rdidx1, + BUFSIZE - ts->size1); + r = read(ts->sockfd, ts->buf1 + ts->rdidx1, maxlen); + if (!r || (r < 0 && errno != EINTR)) { + free_session(ts); + ts = next; + continue; + } + if(!*(ts->buf1 + ts->rdidx1 + r - 1)) { + r--; + if(!r) + continue; + } + ts->rdidx1 += r; + ts->size1 += r; + if (ts->rdidx1 == BUFSIZE) + ts->rdidx1 = 0; + } + + if (ts->size2 < BUFSIZE && FD_ISSET(ts->ptyfd, &rdfdset)) { + /* Read from pty to buffer 2. */ + maxlen = MIN(BUFSIZE - ts->rdidx2, + BUFSIZE - ts->size2); + r = read(ts->ptyfd, ts->buf2 + ts->rdidx2, maxlen); + if (!r || (r < 0 && errno != EINTR)) { + free_session(ts); + ts = next; + continue; + } + ts->rdidx2 += r; + ts->size2 += r; + if (ts->rdidx2 == BUFSIZE) + ts->rdidx2 = 0; + } + + if (ts->size1 == 0) { + ts->rdidx1 = 0; + ts->wridx1 = 0; + } + if (ts->size2 == 0) { + ts->rdidx2 = 0; + ts->wridx2 = 0; + } + ts = next; + } + + } while (1); + + return 0; +} diff --git a/procps/top.c b/procps/top.c index f6bbb23cd..06ae77119 100644 --- a/procps/top.c +++ b/procps/top.c @@ -1,60 +1,330 @@ /* * A tiny 'top' utility. * - * This is written specifically for the linux /proc//status - * file format, but it checks that the file actually conforms to the - * format that this utility expects. - - * This reads the PIDs of all processes at startup and then shows the - * status of those processes at given intervals. User can give - * maximum number of processes to show. If a process exits, it's PID - * is shown as 'EXIT'. If new processes are started while this works, - * it doesn't add them to the list of shown processes. + * This is written specifically for the linux /proc//stat(m) + * files format. + + * This reads the PIDs of all processes and their status and shows + * the status of processes (first ones that fit to screen) at given + * intervals. * * NOTES: * - At startup this changes to /proc, all the reads are then * relative to that. - * - Includes code from the scandir() manual page. - * - * TODO: - * - ppid, uid etc could be read only once when program starts - * and rest of the information could be gotten from the - * /proc//statm file. - * - Add process CPU and memory usage *percentages*. * * (C) Eero Tamminen + * + * Rewroted by Vladimir Oleynik (C) 2002 + */ + +/* Original code Copyrights */ +/* + * Copyright (c) 1992 Branko Lankester + * Copyright (c) 1992 Roger Binns + * Copyright (C) 1994-1996 Charles L. Blake. + * Copyright (C) 1992-1998 Michael K. Johnson + * May be distributed under the conditions of the + * GNU Library General Public License */ + +#include #include #include #include #include #include #include +#include +/* get page info */ +#include #include "busybox.h" +//#define FEATURE_CPU_USAGE_PERCENTAGE /* + 2k */ + +#ifdef FEATURE_CPU_USAGE_PERCENTAGE +#include +#include +#include +#include /* htons */ +#endif + -/* process information taken from /proc, - * The code takes into account how long the fields below are, - * starting from copying the file from 'status' file to displaying it! - */ typedef struct { - char uid[6]; /* User ID */ - char pid[6]; /* Pid */ - char ppid[6]; /* Parent Pid */ - char name[12]; /* Name */ - char cmd[20]; /* command line[read/show size] */ - char state[2]; /* State: S, W... */ - char size[9]; /* VmSize */ - char lck[9]; /* VmLck */ - char rss[9]; /* VmRSS */ - char data[9]; /* VmData */ - char stk[9]; /* VmStk */ - char exe[9]; /* VmExe */ - char lib[9]; /* VmLib */ + int pid; + char user[9]; + char state[4]; + unsigned long rss; + int ppid; +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + unsigned pcpu; + unsigned long stime, utime; +#endif + char *cmd; + + /* basename of executable file in call to exec(2), + size from kernel headers */ + char short_cmd[16]; } status_t; +typedef int (*cmp_t)(status_t *P, status_t *Q); + +static status_t *top; /* Hehe */ +static int ntop; + + +static int pid_sort (status_t *P, status_t *Q) +{ + int p = P->pid; + int q = Q->pid; + + if( p < q ) return -1; + if( p > q ) return 1; + return 0; +} + +static int mem_sort (status_t *P, status_t *Q) +{ + long p = P->rss; + long q = Q->rss; + + if( p > q ) return -1; + if( p < q ) return 1; + return 0; +} + +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + +#define sort_depth 3 +static cmp_t sort_function[sort_depth]; + +static int pcpu_sort (status_t *P, status_t *Q) +{ + int p = P->pcpu; + int q = Q->pcpu; + + if( p > q ) return -1; + if( p < q ) return 1; + return 0; +} + +static int time_sort (status_t *P, status_t *Q) +{ + long p = P->stime; + long q = Q->stime; + + p += P->utime; + q += Q->utime; + if( p > q ) return -1; + if( p < q ) return 1; + return 0; +} + +int mult_lvl_cmp(void* a, void* b) { + int i, cmp_val; + + for(i = 0; i < sort_depth; i++) { + cmp_val = (*sort_function[i])(a, b); + if (cmp_val != 0) + return cmp_val; + } + return 0; +} + +/* This structure stores some critical information from one frame to + the next. mostly used for sorting. Added cumulative and resident fields. */ +struct save_hist { + int ticks; + int pid; + int utime; + int stime; +}; + +/* + * Calculates percent cpu usage for each task. + */ + +static struct save_hist *save_history; + +static unsigned long Hertz; + +/*********************************************************************** + * Some values in /proc are expressed in units of 1/HZ seconds, where HZ + * is the kernel clock tick rate. One of these units is called a jiffy. + * The HZ value used in the kernel may vary according to hacker desire. + * According to Linus Torvalds, this is not true. He considers the values + * in /proc as being in architecture-dependant units that have no relation + * to the kernel clock tick rate. Examination of the kernel source code + * reveals that opinion as wishful thinking. + * + * In any case, we need the HZ constant as used in /proc. (the real HZ value + * may differ, but we don't care) There are several ways we could get HZ: + * + * 1. Include the kernel header file. If it changes, recompile this library. + * 2. Use the sysconf() function. When HZ changes, recompile the C library! + * 3. Ask the kernel. This is obviously correct... + * + * Linus Torvalds won't let us ask the kernel, because he thinks we should + * not know the HZ value. Oh well, we don't have to listen to him. + * Someone smuggled out the HZ value. :-) + * + * This code should work fine, even if Linus fixes the kernel to match his + * stated behavior. The code only fails in case of a partial conversion. + * + */ + +#define FILE_TO_BUF(filename, fd) do{ \ + if (fd == -1 && (fd = open(filename, O_RDONLY)) == -1) { \ + perror_msg_and_die("/proc not be mounted?"); \ + } \ + lseek(fd, 0L, SEEK_SET); \ + if ((local_n = read(fd, buf, sizeof buf - 1)) < 0) { \ + perror_msg_and_die("%s", filename); \ + } \ + buf[local_n] = '\0'; \ +}while(0) + +#define FILE_TO_BUF2(filename, fd) do{ \ + lseek(fd, 0L, SEEK_SET); \ + if ((local_n = read(fd, buf, sizeof buf - 1)) < 0) { \ + perror_msg_and_die("%s", filename); \ + } \ + buf[local_n] = '\0'; \ +}while(0) + +static void init_Hertz_value(void) { + unsigned long user_j, nice_j, sys_j, other_j; /* jiffies (clock ticks) */ + double up_1, up_2, seconds; + unsigned long jiffies, h; + char buf[80]; + int uptime_fd = -1; + int stat_fd = -1; + + long smp_num_cpus = sysconf(_SC_NPROCESSORS_CONF); + + if(smp_num_cpus<1) smp_num_cpus=1; + do { + int local_n; + + FILE_TO_BUF("uptime", uptime_fd); + up_1 = strtod(buf, 0); + FILE_TO_BUF("stat", stat_fd); + sscanf(buf, "cpu %lu %lu %lu %lu", &user_j, &nice_j, &sys_j, &other_j); + FILE_TO_BUF2("uptime", uptime_fd); + up_2 = strtod(buf, 0); + } while((long)( (up_2-up_1)*1000.0/up_1 )); /* want under 0.1% error */ + + close(uptime_fd); + close(stat_fd); + + jiffies = user_j + nice_j + sys_j + other_j; + seconds = (up_1 + up_2) / 2; + h = (unsigned long)( (double)jiffies/seconds/smp_num_cpus ); + /* actual values used by 2.4 kernels: 32 64 100 128 1000 1024 1200 */ + switch(h){ + case 30 ... 34 : Hertz = 32; break; /* ia64 emulator */ + case 48 ... 52 : Hertz = 50; break; + case 58 ... 62 : Hertz = 60; break; + case 63 ... 65 : Hertz = 64; break; /* StrongARM /Shark */ + case 95 ... 105 : Hertz = 100; break; /* normal Linux */ + case 124 ... 132 : Hertz = 128; break; /* MIPS, ARM */ + case 195 ... 204 : Hertz = 200; break; /* normal << 1 */ + case 253 ... 260 : Hertz = 256; break; + case 295 ... 304 : Hertz = 300; break; /* 3 cpus */ + case 393 ... 408 : Hertz = 400; break; /* normal << 2 */ + case 495 ... 504 : Hertz = 500; break; /* 5 cpus */ + case 595 ... 604 : Hertz = 600; break; /* 6 cpus */ + case 695 ... 704 : Hertz = 700; break; /* 7 cpus */ + case 790 ... 808 : Hertz = 800; break; /* normal << 3 */ + case 895 ... 904 : Hertz = 900; break; /* 9 cpus */ + case 990 ... 1010 : Hertz = 1000; break; /* ARM */ + case 1015 ... 1035 : Hertz = 1024; break; /* Alpha, ia64 */ + case 1095 ... 1104 : Hertz = 1100; break; /* 11 cpus */ + case 1180 ... 1220 : Hertz = 1200; break; /* Alpha */ + default: + /* If 32-bit or big-endian (not Alpha or ia64), assume HZ is 100. */ + Hertz = (sizeof(long)==sizeof(int) || htons(999)==999) ? 100UL : 1024UL; + } +} + +static void do_stats(void) +{ + struct timeval t; + static struct timeval oldtime; + struct timezone timez; + float elapsed_time; + + status_t *cur; + int total_time, i, n; + static int prev_count; + int systime, usrtime, pid; + + struct save_hist *New_save_hist; + + /* + * Finds the current time (in microseconds) and calculates the time + * elapsed since the last update. + */ + gettimeofday(&t, &timez); + elapsed_time = (t.tv_sec - oldtime.tv_sec) + + (float) (t.tv_usec - oldtime.tv_usec) / 1000000.0; + oldtime.tv_sec = t.tv_sec; + oldtime.tv_usec = t.tv_usec; + + New_save_hist = alloca(sizeof(struct save_hist)*ntop); + /* + * Make a pass through the data to get stats. + */ + for(n = 0; n < ntop; n++) { + cur = top + n; + + /* + * Calculate time in cur process. Time is sum of user time + * (usrtime) plus system time (systime). + */ + systime = cur->stime; + usrtime = cur->utime; + pid = cur->pid; + total_time = systime + usrtime; + New_save_hist[n].ticks = total_time; + New_save_hist[n].pid = pid; + New_save_hist[n].stime = systime; + New_save_hist[n].utime = usrtime; + + /* find matching entry from previous pass */ + for (i = 0; i < prev_count; i++) { + if (save_history[i].pid == pid) { + total_time -= save_history[i].ticks; + systime -= save_history[i].stime; + usrtime -= save_history[i].utime; + break; + } + } + + /* + * Calculate percent cpu time for cur task. + */ + i = (total_time * 10 * 100/Hertz) / elapsed_time; + if (i > 999) + i = 999; + cur->pcpu = i; + + } + + /* + * Save cur frame's information. + */ + free(save_history); + save_history = memcpy(xmalloc(sizeof(struct save_hist)*n), New_save_hist, + sizeof(struct save_hist)*n); + prev_count = n; + qsort(top, n, sizeof(status_t), (void*)mult_lvl_cmp); +} +#else +static cmp_t sort_function; +#endif /* FEATURE_CPU_USAGE_PERCENTAGE */ + /* display generic info (meminfo / loadavg) */ -static void display_generic(void) +static unsigned long display_generic(void) { FILE *fp; char buf[80]; @@ -62,303 +332,245 @@ static void display_generic(void) unsigned long total, used, mfree, shared, buffers, cached; /* read memory info */ - fp = fopen("meminfo", "r"); - if (!fp) { - perror("fopen('meminfo')"); - return; - } + fp = xfopen("meminfo", "r"); fgets(buf, sizeof(buf), fp); /* skip first line */ if (fscanf(fp, "Mem: %lu %lu %lu %lu %lu %lu", &total, &used, &mfree, &shared, &buffers, &cached) != 6) { - fprintf(stderr, "Error: failed to read 'meminfo'"); - fclose(fp); + error_msg_and_die("failed to read '%s'", "meminfo"); } fclose(fp); /* read load average */ - fp = fopen("loadavg", "r"); - if (!fp) { - perror("fopen('loadavg')"); - return; - } + fp = xfopen("loadavg", "r"); if (fscanf(fp, "%f %f %f", &avg1, &avg2, &avg3) != 3) { - fprintf(stderr, "Error: failed to read 'loadavg'"); - fclose(fp); - return; + error_msg_and_die("failed to read '%s'", "loadavg"); } fclose(fp); /* convert to kilobytes */ - if (total) total /= 1024; - if (used) used /= 1024; - if (mfree) mfree /= 1024; - if (shared) shared /= 1024; - if (buffers) buffers /= 1024; - if (cached) cached /= 1024; + used /= 1024; + mfree /= 1024; + shared /= 1024; + buffers /= 1024; + cached /= 1024; /* output memory info and load average */ - printf("Mem: %ldK, %ldK used, %ldK free, %ldK shrd, %ldK buff, %ldK cached\n", - total, used, mfree, shared, buffers, cached); - printf("Load average: %.2f, %.2f, %.2f (State: S=sleeping R=running, W=waiting)\n", + /* clear screen & go to top */ + printf("\e[H\e[J" "Mem: " + "%ldK used, %ldK free, %ldK shrd, %ldK buff, %ldK cached\n", + used, mfree, shared, buffers, cached); + printf("Load average: %.2f, %.2f, %.2f " + "(State: S=sleeping R=running, W=waiting)\n", avg1, avg2, avg3); + return total / 1024; } /* display process statuses */ -static void display_status(int count, const status_t *s) +static void display_status(int count, int col) { - const char *fmt, *cmd; - - /* clear screen & go to top */ - printf("\e[2J\e[1;1H"); - - display_generic(); + status_t *s = top; + char rss_str_buf[8]; + unsigned long total_memory = display_generic(); +#ifdef FEATURE_CPU_USAGE_PERCENTAGE /* what info of the processes is shown */ - printf("\n%*s %*s %*s %*s %*s %*s %-*s\n", - sizeof(s->pid)-1, "Pid:", - sizeof(s->state)-1, "", - sizeof(s->ppid)-1, "PPid:", - sizeof(s->uid)-1, "UID:", - sizeof(s->size)-1, "WmSize:", - sizeof(s->rss)-1, "WmRSS:", - sizeof(s->cmd)-1, "command line:"); + printf("\n\e[7m PID USER STATUS RSS PPID %%CPU %%MEM COMMAND\e[0m\n"); +#else + printf("\n\e[7m PID USER STATUS RSS PPID %%MEM COMMAND\e[0m\n"); +#endif while (count--) { - if (s->cmd[0]) { - /* normal process, has command line */ - cmd = s->cmd; - fmt = "%*s %*s %*s %*s %*s %*s %s\n"; - } else { - /* no command line, show only process name */ - cmd = s->name; - fmt = "%*s %*s %*s %*s %*s %*s [%s]\n"; - } - printf(fmt, - sizeof(s->pid)-1, s->pid, - sizeof(s->state)-1, s->state, - sizeof(s->ppid)-1, s->ppid, - sizeof(s->uid)-1, s->uid, - sizeof(s->size)-1, s->size, - sizeof(s->rss)-1, s->rss, - cmd); - s++; - } -} + char *namecmd = s->cmd; + int pmem; - -/* checks if given 'buf' for process starts with 'id' + ':' + TAB - * and stores rest of the buf to 'store' with max size 'size' - */ -static int process_status(const char *buf, const char *id, char *store, size_t size) -{ - int len, i; + pmem = 1000.0 * s->rss / total_memory; + if (pmem > 999) pmem = 999; - /* check status field name */ - len = strlen(id); - if (strncmp(buf, id, len) != 0) { - if(store) - error_msg_and_die("ERROR status: line doesn't start with '%s' in:\n%s\n", id, buf); + if(s->rss > 10*1024) + sprintf(rss_str_buf, "%6ldM", s->rss/1024); else - return 0; - } - if (!store) { - /* ignoring this field */ - return 1; - } - buf += len; - - /* check status field format */ - if ((*buf++ != ':') || (*buf++ != '\t')) { - error_msg_and_die("ERROR status: field '%s' not followed with ':' + TAB in:\n%s\n", id, buf); - } - - /* skip whitespace in Wm* fields */ - if (id[0] == 'V' && id[1] == 'm') { - i = 3; - while (i--) { - if (*buf == ' ') { - buf++; + sprintf(rss_str_buf, "%7ld", s->rss); +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + printf("%5d %-8s %s %s %5d %2d.%d %2u.%u ", +#else + printf("%5d %-8s %s %s %5d %2u.%u ", +#endif + s->pid, s->user, s->state, rss_str_buf, s->ppid, +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + s->pcpu/10, s->pcpu%10, +#endif + pmem/10, pmem%10); + if(namecmd != 0 && namecmd[0] != 0) { + if(strlen(namecmd) > col) + namecmd[col] = 0; + printf("%s\n", namecmd); } else { - error_msg_and_die("ERROR status: can't skip whitespace for " - "'%s' field in:\n%s\n", id, buf); + namecmd = s->short_cmd; + if(strlen(namecmd) > (col-2)) + namecmd[col-2] = 0; + printf("[%s]\n", namecmd); } + s++; } - } - - /* copy at max (size-1) chars and force '\0' to the end */ - while (--size) { - if (*buf < ' ') { - break; - } - *store++ = *buf++; - } - *store = '\0'; - return 1; } -/* read process statuses */ -static void read_status(int num, status_t *s) +/* returns true for file names which are PID dirs + * (i.e. start with number) + */ +static int filter_pids(const struct dirent *dir) { + char *name = dir->d_name; + int n; char status[20]; - char buf[80]; + char buf[1024]; FILE *fp; + status_t curstatus; + int pid; + long tasknice; + struct stat sb; + + if (!(*name >= '0' && *name <= '9')) + return 0; + if(stat(name, &sb)) + return 0; + + memset(&curstatus, 0, sizeof(status_t)); + pid = atoi(name); + curstatus.pid = pid; - while (num--) { - sprintf(status, "%s/status", s->pid); - - /* read the command line from 'cmdline' in PID dir */ - fp = fopen(status, "r"); - if (!fp) { - strncpy(s->pid, "EXIT", sizeof(s->pid)); - s->pid[sizeof(s->pid)-1] = '\0'; + my_getpwuid(curstatus.user, sb.st_uid); + + sprintf(status, "%d/stat", pid); + if((fp = fopen(status, "r")) == NULL) + return 0; + name = fgets(buf, sizeof(buf), fp); fclose(fp); - continue; - } + if(name == NULL) + return 0; + name = strrchr(buf, ')'); /* split into "PID (cmd" and "" */ + if(name == 0 || name[1] != ' ') + return 0; + *name = 0; + sscanf(buf, "%*s (%15c", curstatus.short_cmd); + n = sscanf(name+2, + "%c %d " + "%*s %*s %*s %*s " /* pgrp, session, tty, tpgid */ + "%*s %*s %*s %*s %*s " /* flags, min_flt, cmin_flt, maj_flt, cmaj_flt */ +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + "%lu %lu " +#else + "%*s %*s " +#endif + "%*s %*s %*s " /* cutime, cstime, priority */ + "%ld " + "%*s %*s %*s " /* timeout, it_real_value, start_time */ + "%*s " /* vsize */ + "%ld", + curstatus.state, &curstatus.ppid, +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + &curstatus.utime, &curstatus.stime, +#endif + &tasknice, + &curstatus.rss); +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + if(n != 6) +#else + if(n != 4) +#endif + return 0; + + if (curstatus.rss == 0 && curstatus.state[0] != 'Z') + curstatus.state[1] = 'W'; + else + curstatus.state[1] = ' '; + if (tasknice < 0) + curstatus.state[2] = '<'; + else if (tasknice > 0) + curstatus.state[2] = 'N'; + else + curstatus.state[2] = ' '; + + curstatus.rss <<= (PAGE_SHIFT - 10); /* 2**10 = 1kb */ - /* get and process the information */ - fgets(buf, sizeof(buf), fp); - process_status(buf, "Name", s->name, sizeof(s->name)); - fgets(buf, sizeof(buf), fp); - process_status(buf, "State", s->state, sizeof(s->state)); - fgets(buf, sizeof(buf), fp); - if(process_status(buf, "Tgid", NULL, 0)) - fgets(buf, sizeof(buf), fp); - process_status(buf, "Pid", NULL, 0); - fgets(buf, sizeof(buf), fp); - process_status(buf, "PPid", s->ppid, sizeof(s->ppid)); - fgets(buf, sizeof(buf), fp); - if(process_status(buf, "TracerPid", NULL, 0)) - fgets(buf, sizeof(buf), fp); - process_status(buf, "Uid", s->uid, sizeof(s->uid)); - fgets(buf, sizeof(buf), fp); - process_status(buf, "Gid", NULL, 0); - fgets(buf, sizeof(buf), fp); - if(process_status(buf, "FDSize", NULL, 0)) - fgets(buf, sizeof(buf), fp); - process_status(buf, "Groups", NULL, 0); - fgets(buf, sizeof(buf), fp); - /* only user space processes have command line - * and memory statistics - */ - if (s->cmd[0]) { - process_status(buf, "VmSize", s->size, sizeof(s->size)); - fgets(buf, sizeof(buf), fp); - process_status(buf, "VmLck", s->lck, sizeof(s->lck)); - fgets(buf, sizeof(buf), fp); - process_status(buf, "VmRSS", s->rss, sizeof(s->rss)); - fgets(buf, sizeof(buf), fp); - process_status(buf, "VmData", s->data, sizeof(s->data)); - fgets(buf, sizeof(buf), fp); - process_status(buf, "VmStk", s->stk, sizeof(s->stk)); - fgets(buf, sizeof(buf), fp); - process_status(buf, "VmExe", s->exe, sizeof(s->exe)); - fgets(buf, sizeof(buf), fp); - process_status(buf, "VmLib", s->lib, sizeof(s->lib)); + sprintf(status, "%d/cmdline", pid); + if((fp = fopen(status, "r")) == NULL) + return 0; + if(fgets(buf, sizeof(buf), fp) != NULL) { + name = strchr(buf, '\n'); + if(name != NULL) + *name = 0; + if(buf[0]) + curstatus.cmd = strdup(buf); /* if NULL it work true also */ } fclose(fp); - /* next process */ - s++; - } + n = ntop; + top = xrealloc(top, (++ntop)*sizeof(status_t)); + memcpy(top + n, &curstatus, sizeof(status_t)); + return 1; } -/* allocs statuslist and reads process command lines, frees namelist, - * returns filled statuslist or NULL in case of error. - */ -static status_t *read_info(int num, struct dirent **namelist) -{ - status_t *statuslist, *s; - char cmdline[20]; - FILE *fp; - int idx; +static struct dirent **namelist; - /* allocate & zero status for each of the processes */ - statuslist = calloc(num, sizeof(status_t)); - if (!statuslist) { - return NULL; - } - - /* go through the processes */ - for (idx = 0; idx < num; idx++) { - - /* copy PID string to status struct and free name */ - s = &(statuslist[idx]); - if (strlen(namelist[idx]->d_name) > sizeof(s->pid)-1) { - fprintf(stderr, "PID '%s' too long\n", namelist[idx]->d_name); - return NULL; - } - strncpy(s->pid, namelist[idx]->d_name, sizeof(s->pid)); - s->pid[sizeof(s->pid)-1] = '\0'; - free(namelist[idx]); - - /* read the command line from 'cmdline' in PID dir */ - sprintf(cmdline, "%s/cmdline", s->pid); - fp = fopen(cmdline, "r"); - if (!fp) { - fclose(fp); - perror("fopen('cmdline')"); - return NULL; - } - fgets(statuslist[idx].cmd, sizeof(statuslist[idx].cmd), fp); - fclose(fp); +static void clearmems(void) { + int i; + + for(i = 0; i < ntop; i++) { + free(top[i].cmd); + free(namelist[i]); } + free(top); free(namelist); - return statuslist; + top = 0; + namelist = 0; + ntop = 0; } +#if defined CONFIG_FEATURE_USE_TERMIOS +#include +#include +#include -/* returns true for file names which are PID dirs - * (i.e. start with number) - */ -static int filter_pids(const struct dirent *dir) -{ - status_t dummy; - char *name = dir->d_name; - - if (*name >= '0' && *name <= '9') { - if (strlen(name) > sizeof(dummy.pid)-1) { - fprintf(stderr, "PID name '%s' too long\n", name); - return 0; - } - return 1; - } - return 0; -} +static struct termios initial_settings; -/* compares two directory entry names as numeric strings - */ -static int num_sort(const void *a, const void *b) +static void reset_term(void) { - int ia = atoi((*(struct dirent **)a)->d_name); - int ib = atoi((*(struct dirent **)b)->d_name); + tcsetattr(0, TCSANOW, (void *) &initial_settings); +#ifdef CONFIG_FEATURE_CLEAN_UP + clearmems(); +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + free(save_history); +#endif +#endif /* CONFIG_FEATURE_CLEAN_UP */ +} - if (ia == ib) { - return 0; - } - /* NOTE: by switching the check, you change the process sort order */ - if (ia < ib) { - return -1; - } else { - return 1; - } +static void sig_catcher (int sig) +{ + reset_term(); } +#endif /* CONFIG_FEATURE_USE_TERMIOS */ + int top_main(int argc, char **argv) { - status_t *statuslist; - struct dirent **namelist; - int opt, num, interval, lines; -#if defined CONFIG_FEATURE_AUTOWIDTH && defined CONFIG_FEATURE_USE_TERMIOS + int opt, interval, lines, col; +#if defined CONFIG_FEATURE_USE_TERMIOS + struct termios new_settings; + struct timeval tv; + fd_set readfds; + unsigned char c; + struct sigaction sa; +#if defined CONFIG_FEATURE_AUTOWIDTH struct winsize win = { 0, 0, 0, 0 }; #endif +#endif /* CONFIG_FEATURE_USE_TERMIOS */ + /* Default update rate is 5 seconds */ interval = 5; - /* Default to 25 lines - 5 lines for status */ - lines = 25 - 5; /* do normal option parsing */ while ((opt = getopt(argc, argv, "d:")) > 0) { @@ -371,42 +583,121 @@ int top_main(int argc, char **argv) } } -#if defined CONFIG_FEATURE_AUTOWIDTH && defined CONFIG_FEATURE_USE_TERMIOS - ioctl(fileno(stdout), TIOCGWINSZ, &win); - if (win.ws_row > 4) - lines = win.ws_row - 5; + /* Default to 25 lines - 5 lines for status */ + lines = 25 - 5; + /* Default CMD format size */ +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + col = 35 - 6; +#else + col = 35; #endif - /* change to proc */ if (chdir("/proc") < 0) { perror_msg_and_die("chdir('/proc')"); } - - /* read process IDs for all the processes from the procfs */ - num = scandir(".", &namelist, filter_pids, num_sort); - if (num < 0) { +#if defined CONFIG_FEATURE_USE_TERMIOS + tcgetattr(0, (void *) &initial_settings); + memcpy(&new_settings, &initial_settings, sizeof(struct termios)); + new_settings.c_lflag &= ~(ISIG | ICANON); /* unbuffered input */ + /* Turn off echoing */ + new_settings.c_lflag &= ~(ECHO | ECHONL); + + signal (SIGTERM, sig_catcher); + sigaction (SIGTERM, (struct sigaction *) 0, &sa); + sa.sa_flags |= SA_RESTART; + sa.sa_flags &= ~SA_INTERRUPT; + sigaction (SIGTERM, &sa, (struct sigaction *) 0); + sigaction (SIGINT, &sa, (struct sigaction *) 0); + tcsetattr(0, TCSANOW, (void *) &new_settings); + atexit(reset_term); +#if defined CONFIG_FEATURE_AUTOWIDTH + ioctl(0, TIOCGWINSZ, &win); + if (win.ws_row > 4) { + lines = win.ws_row - 5; +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + col = win.ws_col - 80 + 35 - 6; +#else + col = win.ws_col - 80 + 35; +#endif + } +#endif +#endif /* CONFIG_FEATURE_USE_TERMIOS */ +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + sort_function[0] = pcpu_sort; + sort_function[1] = mem_sort; + sort_function[2] = time_sort; +#else + sort_function = mem_sort; +#endif + while (1) { + /* read process IDs & status for all the processes */ + if (scandir(".", &namelist, filter_pids, 0) < 0) { perror_msg_and_die("scandir('/proc')"); } - if (lines > num) { - lines = num; +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + if(!Hertz) { + init_Hertz_value(); + do_stats(); + sleep(1); + clearmems(); + continue; } - - /* read command line for each of the processes */ - statuslist = read_info(num, namelist); - if (!statuslist) { + do_stats(); +#else + qsort(top, ntop, sizeof(status_t), (void*)sort_function); +#endif + opt = lines; + if (opt > ntop) { + opt = ntop; + } + /* show status for each of the processes */ + display_status(opt, col); +#if defined CONFIG_FEATURE_USE_TERMIOS + tv.tv_sec = interval; + tv.tv_usec = 0; + FD_ZERO (&readfds); + FD_SET (0, &readfds); + select (1, &readfds, NULL, NULL, &tv); + if (FD_ISSET (0, &readfds)) { + if (read (0, &c, 1) <= 0) { /* signal */ return EXIT_FAILURE; } - - while (1) { - /* read status for each of the processes */ - read_status(num, statuslist); - - /* display status */ - display_status(lines, statuslist); - + if(c == 'q' || c == initial_settings.c_cc[VINTR]) + return EXIT_SUCCESS; + if(c == 'M') { +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + sort_function[0] = mem_sort; + sort_function[1] = pcpu_sort; + sort_function[2] = time_sort; +#else + sort_function = mem_sort; +#endif + } +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + if(c == 'P') { + sort_function[0] = pcpu_sort; + sort_function[1] = mem_sort; + sort_function[2] = time_sort; + } + if(c == 'T') { + sort_function[0] = time_sort; + sort_function[1] = mem_sort; + sort_function[2] = pcpu_sort; + } +#endif + if(c == 'N') { +#ifdef FEATURE_CPU_USAGE_PERCENTAGE + sort_function[0] = pid_sort; +#else + sort_function = pid_sort; +#endif + } + } +#else sleep(interval); +#endif /* CONFIG_FEATURE_USE_TERMIOS */ + clearmems(); } - free(statuslist); return EXIT_SUCCESS; } -- 2.25.1