2 * Top users/processes display for Unix
5 * This program may be freely redistributed,
6 * but this entire comment MUST remain intact.
8 * Copyright (c) 1984, 1989, William LeFebvre, Rice University
9 * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University
11 * $FreeBSD: src/contrib/top/utils.c,v 1.3.6.1 2002/08/11 17:09:25 dwmalone Exp $
12 * $DragonFly: src/contrib/top/utils.c,v 1.3 2003/07/11 23:33:24 dillon Exp $
16 * This file contains various handy utilities used by top.
24 atoiwi(const char *str)
31 if (strncmp(str, "infinity", len) == 0 ||
32 strncmp(str, "all", len) == 0 ||
33 strncmp(str, "maximum", len) == 0)
37 else if (str[0] == '-')
50 * ltoa - convert integer (decimal) to ascii string for positive numbers
51 * only (we don't bother with negative numbers since we know we
58 static char buffer[32];
60 ptr = buffer + sizeof(buffer);
68 *--ptr = (val % 10) + '0';
75 * ltoa7(val) - like ltoa, except the number is right justified in a 7
76 * character field. This code is a duplication of ltoa instead of
77 * a front end to a more general routine for efficiency.
84 static char buffer[32]; /* result is built here */
85 /* 16 is sufficient since the largest number
86 we will ever convert will be 2^32-1,
87 which is 10 digits. */
89 ptr = buffer + sizeof(buffer);
97 *--ptr = (val % 10) + '0';
100 while (ptr > buffer + sizeof(buffer) - 7)
108 * digits(val) - return number of decimal digits in val. Only works for
109 * positive numbers. If val <= 0 then digits(val) == 0.
126 * strecpy(to, from) - copy string "from" into "to" and return a pointer
127 * to the END of the string "to".
131 strecpy(char *to, const char *from)
133 while ((*to++ = *from++) != '\0');
138 * string_index(string, array) - find string in array and return index
142 string_index(char *string, const char **array)
146 while (*array != NULL)
148 if (strcmp(string, *array) == 0)
159 * argparse(line, cntp) - parse arguments in string "line", separating them
160 * out into an argv-like array, and setting *cntp to the number of
161 * arguments encountered. This is a simple parser that doesn't understand
162 * squat about quotes.
166 argparse(char *line, int *cntp)
174 register char **argv;
178 /* unfortunately, the only real way to do this is to go thru the
179 input string twice. */
181 /* step thru the string counting the white space sections */
183 lastch = cnt = length = 0;
184 while ((ch = *from++) != '\0')
187 if (ch == ' ' && lastch != ' ')
194 /* add three to the count: one for the initial "dummy" argument,
195 one for the last argument and one for NULL */
198 /* allocate a char * array to hold the pointers */
199 argarray = (char **)malloc(cnt * sizeof(char *));
201 /* allocate another array to hold the strings themselves */
202 args = (char *)malloc(length+2);
204 /* initialization for main loop */
210 /* create a dummy argument to keep getopt happy */
215 /* now build argv while copying characters */
217 while ((ch = *from++) != '\0')
233 /* set cntp and return the allocated array */
239 * percentages(cnt, out, new, old, diffs) - calculate percentage change
240 * between array "old" and "new", putting the percentages i "out".
241 * "cnt" is size of each array and "diffs" is used for scratch space.
242 * The array "old" is updated on each call.
243 * The routine assumes modulo arithmetic. This function is especially
244 * useful on BSD mchines for calculating cpu state percentages.
248 percentages(int cnt, int *out, long *new, long *old, long *diffs)
251 register long change;
252 register long total_change;
260 /* calculate changes for each state and the overall change */
261 for (i = 0; i < cnt; i++)
263 if ((change = *new - *old) < 0)
265 /* this only happens when the counter wraps */
267 ((unsigned long)*new-(unsigned long)*old);
269 total_change += (*dp++ = change);
273 /* avoid divide by zero potential */
274 if (total_change == 0)
279 /* calculate percentages based on overall change, rounding up */
280 half_total = total_change / 2l;
282 /* Do not divide by 0. Causes Floating point exception */
284 for (i = 0; i < cnt; i++)
286 *out++ = (int)((*diffs++ * 1000LL + half_total) / total_change);
290 /* return the total in case the caller wants to use it */
291 return(total_change);
295 * errmsg(errnum) - return an error message string appropriate to the
296 * error number "errnum". This is a substitute for the System V
297 * function "strerror". There appears to be no reliable way to
298 * determine if "strerror" exists at compile time, so I make do
299 * by providing something of similar functionality. For those
300 * systems that have strerror and NOT errlist, define
301 * -DHAVE_STRERROR in the module file and this function will
305 /* externs referenced by errmsg */
307 #ifndef HAVE_STRERROR
308 #ifndef SYS_ERRLIST_DECLARED
309 #define SYS_ERRLIST_DECLARED
310 extern char *sys_errlist[];
320 char *msg = strerror(errnum);
326 if (errnum > 0 && errnum < sys_nerr)
328 return((char *)sys_errlist[errnum]);
334 /* format_time(seconds) - format number of seconds into a suitable
335 * display that will fit within 6 characters. Note that this
336 * routine builds its string in a static area. If it needs
337 * to be called more than once without overwriting previous data,
338 * then we will need to adopt a technique similar to the
339 * one used for format_k.
343 We want to keep the output within 6 characters. For low values we use
344 the format mm:ss. For values that exceed 999:59, we switch to a format
345 that displays hours and fractions: hhh.tH. For values that exceed
346 999.9, we use hhhh.t and drop the "H" designator. For values that
347 exceed 9999.9, we use "???".
350 char *format_time(long seconds)
352 static char result[10];
354 /* sanity protection */
355 if (seconds < 0 || seconds > (99999l * 360l))
357 strcpy(result, " ???");
359 else if (seconds >= (1000l * 60l))
361 /* alternate (slow) method displaying hours and tenths */
362 sprintf(result, "%5.1fH", (double)seconds / (double)(60l * 60l));
364 /* It is possible that the sprintf took more than 6 characters.
365 If so, then the "H" appears as result[6]. If not, then there
366 is a \0 in result[6]. Either way, it is safe to step on.
372 /* standard method produces MMM:SS */
373 /* we avoid printf as must as possible to make this quick */
374 snprintf(result, sizeof(result), "%3ld:%02ld",
375 (long)(seconds / 60), (long)(seconds % 60));
381 * format_k(amt) - format a kilobyte memory value, returning a string
382 * suitable for display. Returns a pointer to a static
383 * area that changes each call. "amt" is converted to a
384 * string with a trailing "K". If "amt" is 10000 or greater,
385 * then it is formatted as megabytes (rounded) with a
390 * Compromise time. We need to return a string, but we don't want the
391 * caller to have to worry about freeing a dynamically allocated string.
392 * Unfortunately, we can't just return a pointer to a static area as one
393 * of the common uses of this function is in a large call to sprintf where
394 * it might get invoked several times. Our compromise is to maintain an
395 * array of strings and cycle thru them with each invocation. We make the
396 * array large enough to handle the above mentioned case. The constant
397 * NUM_STRINGS defines the number of strings in this array: we can tolerate
398 * up to NUM_STRINGS calls before we start overwriting old information.
399 * Keeping NUM_STRINGS a power of two will allow an intelligent optimizer
400 * to convert the modulo operation into something quicker. What a hack!
403 #define NUM_STRINGS 16
408 static char retarray[NUM_STRINGS][16];
409 static int xindex = 0;
414 p = ret = retarray[xindex];
415 xindex = (xindex + 1) % NUM_STRINGS;
419 amt = (amt + 512) / 1024;
423 amt = (amt + 512) / 1024;
428 p = strecpy(p, ltoa(amt));
438 static char retarray[NUM_STRINGS][32];
439 static int xindex = 0;
444 p = ret = retarray[xindex];
445 xindex = (xindex + 1) % NUM_STRINGS;
449 amt = (amt + 512) / 1024;
453 amt = (amt + 512) / 1024;
457 p = strecpy(p, ltoa(amt));