[BACK]Return to utils.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / top

Annotation of src/usr.bin/top/utils.c, Revision 1.12

1.12    ! deraadt     1: /* $OpenBSD: utils.c,v 1.11 2003/06/19 22:40:45 millert Exp $   */
1.1       downsj      2:
                      3: /*
                      4:  *  Top users/processes display for Unix
                      5:  *  Version 3
                      6:  *
1.6       deraadt     7:  * Copyright (c) 1984, 1989, William LeFebvre, Rice University
                      8:  * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University
1.1       downsj      9:  *
1.6       deraadt    10:  * Redistribution and use in source and binary forms, with or without
                     11:  * modification, are permitted provided that the following conditions
                     12:  * are met:
                     13:  * 1. Redistributions of source code must retain the above copyright
                     14:  *    notice, this list of conditions and the following disclaimer.
                     15:  * 2. Redistributions in binary form must reproduce the above copyright
                     16:  *    notice, this list of conditions and the following disclaimer in the
                     17:  *    documentation and/or other materials provided with the distribution.
                     18:  *
                     19:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     20:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     21:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     22:  * IN NO EVENT SHALL THE AUTHOR OR HIS EMPLOYER BE LIABLE FOR ANY DIRECT, INDIRECT,
                     23:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     24:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     25:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     26:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     27:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     28:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.1       downsj     29:  */
                     30:
                     31: /*
                     32:  *  This file contains various handy utilities used by top.
                     33:  */
                     34:
1.2       downsj     35: #include <sys/types.h>
                     36: #include <stdio.h>
                     37: #include <string.h>
                     38: #include <stdlib.h>
                     39: #include <unistd.h>
                     40:
1.1       downsj     41: #include "top.h"
                     42:
1.9       pvalchev   43: int
                     44: atoiwi(char *str)
1.1       downsj     45: {
1.12    ! deraadt    46:        size_t len;
1.1       downsj     47:
1.10      deraadt    48:        len = strlen(str);
                     49:        if (len != 0) {
                     50:                if (strncmp(str, "infinity", len) == 0 ||
                     51:                    strncmp(str, "all", len) == 0 ||
                     52:                    strncmp(str, "maximum", len) == 0) {
                     53:                        return (Infinity);
                     54:                } else if (str[0] == '-')
                     55:                        return (Invalid);
                     56:                else
                     57:                        return (atoi(str));
1.1       downsj     58:        }
1.10      deraadt    59:        return (0);
1.1       downsj     60: }
                     61:
                     62: /*
1.11      millert    63:  * itoa - convert integer (decimal) to ascii string.
1.1       downsj     64:  */
1.9       pvalchev   65: char *
                     66: itoa(int val)
1.1       downsj     67: {
1.10      deraadt    68:        static char buffer[16]; /* result is built here */
                     69:
                     70:        /*
                     71:         * 16 is sufficient since the largest number we will ever convert
                     72:         * will be 2^32-1, which is 10 digits.
                     73:         */
1.11      millert    74:        (void)snprintf(buffer, sizeof(buffer), "%d", val);
                     75:        return (buffer);
1.1       downsj     76: }
                     77:
                     78: /*
1.11      millert    79:  * format_uid(uid) - like itoa, except for uid_t and the number is right
                     80:  * justified in a 6 character field to match uname_field in top.c.
1.1       downsj     81:  */
1.9       pvalchev   82: char *
1.11      millert    83: format_uid(uid_t uid)
1.1       downsj     84: {
1.11      millert    85:        static char buffer[16]; /* result is built here */
1.1       downsj     86:
1.11      millert    87:        /*
                     88:         * 16 is sufficient since the largest uid we will ever convert
                     89:         * will be 2^32-1, which is 10 digits.
                     90:         */
                     91:        (void)snprintf(buffer, sizeof(buffer), "%6u", uid);
                     92:        return (buffer);
1.1       downsj     93: }
                     94:
                     95: /*
1.10      deraadt    96:  * digits(val) - return number of decimal digits in val.  Only works for
                     97:  * positive numbers.  If val <= 0 then digits(val) == 0.
1.1       downsj     98:  */
1.9       pvalchev   99: int
                    100: digits(int val)
1.1       downsj    101: {
1.10      deraadt   102:        int cnt = 0;
1.1       downsj    103:
1.10      deraadt   104:        while (val > 0) {
                    105:                cnt++;
                    106:                val /= 10;
                    107:        }
                    108:        return (cnt);
1.1       downsj    109: }
                    110:
                    111: /*
                    112:  * string_index(string, array) - find string in array and return index
                    113:  */
1.9       pvalchev  114: int
                    115: string_index(char *string, char **array)
1.1       downsj    116: {
1.10      deraadt   117:        int i = 0;
1.1       downsj    118:
1.10      deraadt   119:        while (*array != NULL) {
                    120:                if (strcmp(string, *array) == 0)
                    121:                        return (i);
                    122:                array++;
                    123:                i++;
1.1       downsj    124:        }
1.10      deraadt   125:        return (-1);
1.1       downsj    126: }
                    127:
                    128: /*
                    129:  * argparse(line, cntp) - parse arguments in string "line", separating them
1.10      deraadt   130:  * out into an argv-like array, and setting *cntp to the number of
                    131:  * arguments encountered.  This is a simple parser that doesn't understand
                    132:  * squat about quotes.
1.1       downsj    133:  */
1.9       pvalchev  134: char **
                    135: argparse(char *line, int *cntp)
1.1       downsj    136: {
1.10      deraadt   137:        char **argv, **argarray, *args, *from, *to;
                    138:        int cnt, ch, length, lastch;
                    139:
                    140:        /*
                    141:         * unfortunately, the only real way to do this is to go thru the
                    142:         * input string twice.
                    143:         */
                    144:
                    145:        /* step thru the string counting the white space sections */
                    146:        from = line;
                    147:        lastch = cnt = length = 0;
                    148:        while ((ch = *from++) != '\0') {
                    149:                length++;
                    150:                if (ch == ' ' && lastch != ' ')
                    151:                        cnt++;
                    152:                lastch = ch;
1.1       downsj    153:        }
                    154:
1.10      deraadt   155:        /*
                    156:         * add three to the count:  one for the initial "dummy" argument, one
                    157:         * for the last argument and one for NULL
                    158:         */
                    159:        cnt += 3;
                    160:
                    161:        /* allocate a char * array to hold the pointers */
                    162:        argarray = (char **) malloc(cnt * sizeof(char *));
                    163:
                    164:        /* allocate another array to hold the strings themselves */
                    165:        args = (char *) malloc(length + 2);
                    166:
                    167:        /* initialization for main loop */
                    168:        from = line;
                    169:        to = args;
                    170:        argv = argarray;
                    171:        lastch = '\0';
                    172:
                    173:        /* create a dummy argument to keep getopt happy */
                    174:        *argv++ = to;
                    175:        *to++ = '\0';
                    176:        cnt = 2;
                    177:
                    178:        /* now build argv while copying characters */
                    179:        *argv++ = to;
                    180:        while ((ch = *from++) != '\0') {
                    181:                if (ch != ' ') {
                    182:                        if (lastch == ' ') {
                    183:                                *to++ = '\0';
                    184:                                *argv++ = to;
                    185:                                cnt++;
                    186:                        }
                    187:                        *to++ = ch;
                    188:                }
                    189:                lastch = ch;
1.1       downsj    190:        }
1.10      deraadt   191:        *to++ = '\0';
                    192:
                    193:        /* set cntp and return the allocated array */
                    194:        *cntp = cnt;
                    195:        return (argarray);
1.1       downsj    196: }
                    197:
                    198: /*
1.10      deraadt   199:  * percentages(cnt, out, new, old, diffs) - calculate percentage change
                    200:  * between array "old" and "new", putting the percentages i "out".
                    201:  * "cnt" is size of each array and "diffs" is used for scratch space.
                    202:  * The array "old" is updated on each call.
                    203:  * The routine assumes modulo arithmetic.  This function is especially
                    204:  * useful on BSD mchines for calculating cpu state percentages.
1.1       downsj    205:  */
1.9       pvalchev  206: int
                    207: percentages(int cnt, int *out, long *new, long *old, long *diffs)
1.1       downsj    208: {
1.10      deraadt   209:        long change, total_change, *dp, half_total;
                    210:        int i;
                    211:
                    212:        /* initialization */
                    213:        total_change = 0;
                    214:        dp = diffs;
                    215:
                    216:        /* calculate changes for each state and the overall change */
                    217:        for (i = 0; i < cnt; i++) {
                    218:                if ((change = *new - *old) < 0) {
                    219:                        /* this only happens when the counter wraps */
                    220:                        change = ((unsigned int)*new - (unsigned int)*old);
                    221:                }
                    222:                total_change += (*dp++ = change);
                    223:                *old++ = *new++;
1.1       downsj    224:        }
                    225:
1.10      deraadt   226:        /* avoid divide by zero potential */
                    227:        if (total_change == 0)
                    228:                total_change = 1;
                    229:
                    230:        /* calculate percentages based on overall change, rounding up */
                    231:        half_total = total_change / 2l;
                    232:        for (i = 0; i < cnt; i++)
                    233:                *out++ = ((*diffs++ * 1000 + half_total) / total_change);
                    234:
                    235:        /* return the total in case the caller wants to use it */
                    236:        return (total_change);
1.1       downsj    237: }
                    238:
1.10      deraadt   239: /*
                    240:  * format_time(seconds) - format number of seconds into a suitable display
                    241:  * that will fit within 6 characters.  Note that this routine builds its
                    242:  * string in a static area.  If it needs to be called more than once without
                    243:  * overwriting previous data, then we will need to adopt a technique similar
                    244:  * to the one used for format_k.
1.1       downsj    245:  */
                    246:
1.10      deraadt   247: /*
                    248:  * Explanation: We want to keep the output within 6 characters.  For low
                    249:  * values we use the format mm:ss.  For values that exceed 999:59, we switch
                    250:  * to a format that displays hours and fractions:  hhh.tH.  For values that
                    251:  * exceed 999.9, we use hhhh.t and drop the "H" designator.  For values that
                    252:  * exceed 9999.9, we use "???".
1.1       downsj    253:  */
                    254:
1.9       pvalchev  255: char *
                    256: format_time(time_t seconds)
1.1       downsj    257: {
1.10      deraadt   258:        static char result[10];
1.1       downsj    259:
1.10      deraadt   260:        /* sanity protection */
                    261:        if (seconds < 0 || seconds > (99999l * 360l)) {
                    262:                strlcpy(result, "   ???", sizeof result);
                    263:        } else if (seconds >= (1000l * 60l)) {
                    264:                /* alternate (slow) method displaying hours and tenths */
                    265:                snprintf(result, sizeof(result), "%5.1fH",
                    266:                    (double) seconds / (double) (60l * 60l));
                    267:
                    268:                /*
                    269:                 * It is possible that the snprintf took more than 6
                    270:                 * characters. If so, then the "H" appears as result[6].  If
                    271:                 * not, then there is a \0 in result[6].  Either way, it is
                    272:                 * safe to step on.
                    273:                 */
                    274:                result[6] = '\0';
                    275:        } else {
                    276:                /* standard method produces MMM:SS */
                    277:                /* we avoid printf as must as possible to make this quick */
                    278:                snprintf(result, sizeof(result), "%3d:%02d", seconds / 60,
                    279:                    seconds % 60);
                    280:        }
                    281:        return (result);
1.1       downsj    282: }
                    283:
                    284: /*
                    285:  * format_k(amt) - format a kilobyte memory value, returning a string
1.10      deraadt   286:  * suitable for display.  Returns a pointer to a static
                    287:  * area that changes each call.  "amt" is converted to a
                    288:  * string with a trailing "K".  If "amt" is 10000 or greater,
                    289:  * then it is formatted as megabytes (rounded) with a
                    290:  * trailing "M".
1.1       downsj    291:  */
                    292:
                    293: /*
                    294:  * Compromise time.  We need to return a string, but we don't want the
                    295:  * caller to have to worry about freeing a dynamically allocated string.
                    296:  * Unfortunately, we can't just return a pointer to a static area as one
1.8       deraadt   297:  * of the common uses of this function is in a large call to snprintf where
1.1       downsj    298:  * it might get invoked several times.  Our compromise is to maintain an
                    299:  * array of strings and cycle thru them with each invocation.  We make the
                    300:  * array large enough to handle the above mentioned case.  The constant
                    301:  * NUM_STRINGS defines the number of strings in this array:  we can tolerate
                    302:  * up to NUM_STRINGS calls before we start overwriting old information.
                    303:  * Keeping NUM_STRINGS a power of two will allow an intelligent optimizer
                    304:  * to convert the modulo operation into something quicker.  What a hack!
                    305:  */
                    306:
                    307: #define NUM_STRINGS 8
                    308:
1.9       pvalchev  309: char *
                    310: format_k(int amt)
1.1       downsj    311: {
1.10      deraadt   312:        static char retarray[NUM_STRINGS][16];
1.12    ! deraadt   313:        static int  idx = 0;
1.11      millert   314:        char *ret, tag = 'K';
1.10      deraadt   315:
1.12    ! deraadt   316:        ret = retarray[idx];
        !           317:        idx = (idx + 1) % NUM_STRINGS;
1.10      deraadt   318:
                    319:        if (amt >= 10000) {
                    320:                amt = (amt + 512) / 1024;
                    321:                tag = 'M';
                    322:                if (amt >= 10000) {
                    323:                        amt = (amt + 512) / 1024;
                    324:                        tag = 'G';
                    325:                }
1.1       downsj    326:        }
1.11      millert   327:        snprintf(ret, sizeof(retarray[0]), "%d%c", amt, tag);
1.10      deraadt   328:        return (ret);
1.1       downsj    329: }