X-Git-Url: https://git.librecmc.org/?a=blobdiff_plain;f=miscutils%2Ftime.c;h=65dbcdcf31ae0edc835a614441b061649430ed22;hb=73af705628ddaedc4c6f7f78b9658d6c01310309;hp=e8473f702c0b2287fa21cc4fcbf5c969b796fbd2;hpb=6ca409e0e4c198fe3081346eebbae3f068fe605a;p=oweals%2Fbusybox.git diff --git a/miscutils/time.c b/miscutils/time.c index e8473f702..65dbcdcf3 100644 --- a/miscutils/time.c +++ b/miscutils/time.c @@ -1,15 +1,37 @@ /* vi: set sw=4 ts=4: */ -/* `time' utility to display resource usage of processes. +/* 'time' utility to display resource usage of processes. Copyright (C) 1990, 91, 92, 93, 96 Free Software Foundation, Inc. - Licensed under GPL version 2, see file LICENSE in this tarball for details. + Licensed under GPLv2, see file LICENSE in this source tree. */ /* Originally written by David Keppel . Heavily modified by David MacKenzie . Heavily modified for busybox by Erik Andersen */ +//config:config TIME +//config: bool "time (7 kb)" +//config: default y +//config: help +//config: The time command runs the specified program with the given arguments. +//config: When the command finishes, time writes a message to standard output +//config: giving timing statistics about this program run. + +//applet:IF_TIME(APPLET(time, BB_DIR_USR_BIN, BB_SUID_DROP)) + +//kbuild:lib-$(CONFIG_TIME) += time.o + +//usage:#define time_trivial_usage +//usage: "[-vpa] [-o FILE] PROG ARGS" +//usage:#define time_full_usage "\n\n" +//usage: "Run PROG, display resource usage when it exits\n" +//usage: "\n -v Verbose" +//usage: "\n -p POSIX output format" +//usage: "\n -f FMT Custom format" +//usage: "\n -o FILE Write result to FILE" +//usage: "\n -a Append (else overwrite)" #include "libbb.h" +#include /* getrusage */ /* Information on the resources used by a child process. */ typedef struct { @@ -28,7 +50,6 @@ static const char default_format[] ALIGN1 = "real\t%E\nuser\t%u\nsys\t%T"; /* The output format for the -p option .*/ static const char posix_format[] ALIGN1 = "real %e\nuser %U\nsys %S"; - /* Format string for printing all statistics verbosely. Keep this output to 24 lines so users on terminals can see it all.*/ static const char long_format[] ALIGN1 = @@ -56,35 +77,31 @@ static const char long_format[] ALIGN1 = "\tPage size (bytes): %Z\n" "\tExit status: %x"; - /* Wait for and fill in data on child process PID. Return 0 on error, 1 if ok. */ - /* pid_t is short on BSDI, so don't try to promote it. */ -static int resuse_end(pid_t pid, resource_t * resp) +static void resuse_end(pid_t pid, resource_t *resp) { - int status; pid_t caught; /* Ignore signals, but don't ignore the children. When wait3 - returns the child process, set the time the command finished. */ - while ((caught = wait3(&status, 0, &resp->ru)) != pid) { - if (caught == -1) - return 0; + * returns the child process, set the time the command finished. */ + while ((caught = wait3(&resp->waitstatus, 0, &resp->ru)) != pid) { + if (caught == -1 && errno != EINTR) { + bb_perror_msg("wait"); + return; + } } - resp->elapsed_ms = (monotonic_us() / 1000) - resp->elapsed_ms; - resp->waitstatus = status; - return 1; + resp->elapsed_ms = monotonic_ms() - resp->elapsed_ms; } -/* Print ARGV, with each entry in ARGV separated by FILLER. */ -static void printargv(char *const *argv, const char *filler) +static void printargv(char *const *argv) { - fputs(*argv, stdout); - while (*++argv) { - fputs(filler, stdout); - fputs(*argv, stdout); - } + const char *fmt = " %s" + 1; + do { + printf(fmt, *argv); + fmt = " %s"; + } while (*++argv); } /* Return the number of kilobytes corresponding to a number of pages PAGES. @@ -94,35 +111,29 @@ static void printargv(char *const *argv, const char *filler) This is funky since the pagesize could be less than 1K. Note: Some machines express getrusage statistics in terms of K, others in terms of pages. */ - -static unsigned long ptok(unsigned long pages) +static unsigned long ptok(const unsigned pagesize, const unsigned long pages) { - static unsigned long ps; unsigned long tmp; - /* Initialization. */ - if (ps == 0) - ps = getpagesize(); - /* Conversion. */ - if (pages > (LONG_MAX / ps)) { /* Could overflow. */ - tmp = pages / 1024; /* Smaller first, */ - return tmp * ps; /* then larger. */ + if (pages > (LONG_MAX / pagesize)) { /* Could overflow. */ + tmp = pages / 1024; /* Smaller first, */ + return tmp * pagesize; /* then larger. */ } /* Could underflow. */ - tmp = pages * ps; /* Larger first, */ - return tmp / 1024; /* then smaller. */ + tmp = pages * pagesize; /* Larger first, */ + return tmp / 1024; /* then smaller. */ } /* summarize: Report on the system use of a command. - Print the FMT argument except that `%' sequences - have special meaning, and `\n' and `\t' are translated into - newline and tab, respectively, and `\\' is translated into `\'. + Print the FMT argument except that '%' sequences + have special meaning, and '\n' and '\t' are translated into + newline and tab, respectively, and '\\' is translated into '\'. - The character following a `%' can be: + The character following a '%' can be: (* means the tcsh time builtin also recognizes it) - % == a literal `%' + % == a literal '%' C == command name and arguments * D == average unshared data size in K (ru_idrss+ru_isrss) * E == elapsed real (wall clock) time in [hour:]min:sec @@ -162,15 +173,18 @@ static unsigned long ptok(unsigned long pages) #define TICKS_PER_SEC 100 #endif -static void summarize(const char *fmt, char **command, resource_t * resp) +static void summarize(const char *fmt, char **command, resource_t *resp) { unsigned vv_ms; /* Elapsed virtual (CPU) milliseconds */ unsigned cpu_ticks; /* Same, in "CPU ticks" */ + unsigned pagesize = getpagesize(); + /* Impossible: we do not use WUNTRACED flag in wait()... if (WIFSTOPPED(resp->waitstatus)) printf("Command stopped by signal %u\n", WSTOPSIG(resp->waitstatus)); - else if (WIFSIGNALED(resp->waitstatus)) + else */ + if (WIFSIGNALED(resp->waitstatus)) printf("Command terminated by signal %u\n", WTERMSIG(resp->waitstatus)); else if (WIFEXITED(resp->waitstatus) && WEXITSTATUS(resp->waitstatus)) @@ -181,15 +195,13 @@ static void summarize(const char *fmt, char **command, resource_t * resp) + (resp->ru.ru_utime.tv_usec + resp->ru.ru_stime.tv_usec) / 1000; #if (1000 / TICKS_PER_SEC) * TICKS_PER_SEC == 1000 - /* 1000 is exactly divisible by TICKS_PER_SEC */ + /* 1000 is exactly divisible by TICKS_PER_SEC (typical) */ cpu_ticks = vv_ms / (1000 / TICKS_PER_SEC); #else cpu_ticks = vv_ms * (unsigned long long)TICKS_PER_SEC / 1000; #endif if (!cpu_ticks) cpu_ticks = 1; /* we divide by it, must be nonzero */ - /* putchar() != putc(stdout) in glibc! */ - while (*fmt) { /* Handle leading literal part */ int n = strcspn(fmt, "%\\"); @@ -205,7 +217,7 @@ static void summarize(const char *fmt, char **command, resource_t * resp) /* Usually we optimize for size, but there is a limit * for everything. With this we do a lot of 1-byte writes */ default: - putc(*fmt, stdout); + bb_putchar(*fmt); break; #endif @@ -215,20 +227,20 @@ static void summarize(const char *fmt, char **command, resource_t * resp) /* Our format strings do not have these */ /* and we do not take format str from user */ default: - putc('%', stdout); + bb_putchar('%'); /*FALLTHROUGH*/ case '%': if (!*fmt) goto ret; - putc(*fmt, stdout); + bb_putchar(*fmt); break; #endif case 'C': /* The command that got timed. */ - printargv(command, " "); + printargv(command); break; case 'D': /* Average unshared data size. */ printf("%lu", - ptok((UL) resp->ru.ru_idrss) / cpu_ticks + - ptok((UL) resp->ru.ru_isrss) / cpu_ticks); + (ptok(pagesize, (UL) resp->ru.ru_idrss) + + ptok(pagesize, (UL) resp->ru.ru_isrss)) / cpu_ticks); break; case 'E': { /* Elapsed real (wall clock) time. */ unsigned seconds = resp->elapsed_ms / 1000; @@ -252,12 +264,12 @@ static void summarize(const char *fmt, char **command, resource_t * resp) break; case 'K': /* Average mem usage == data+stack+text. */ printf("%lu", - ptok((UL) resp->ru.ru_idrss) / cpu_ticks + - ptok((UL) resp->ru.ru_isrss) / cpu_ticks + - ptok((UL) resp->ru.ru_ixrss) / cpu_ticks); + (ptok(pagesize, (UL) resp->ru.ru_idrss) + + ptok(pagesize, (UL) resp->ru.ru_isrss) + + ptok(pagesize, (UL) resp->ru.ru_ixrss)) / cpu_ticks); break; case 'M': /* Maximum resident set size. */ - printf("%lu", ptok((UL) resp->ru.ru_maxrss)); + printf("%lu", ptok(pagesize, (UL) resp->ru.ru_maxrss)); break; case 'O': /* Outputs. */ printf("%lu", resp->ru.ru_oublock); @@ -310,10 +322,10 @@ static void summarize(const char *fmt, char **command, resource_t * resp) printf("%lu", resp->ru.ru_nswap); break; case 'X': /* Average shared text size. */ - printf("%lu", ptok((UL) resp->ru.ru_ixrss) / cpu_ticks); + printf("%lu", ptok(pagesize, (UL) resp->ru.ru_ixrss) / cpu_ticks); break; case 'Z': /* Page size. */ - printf("%u", getpagesize()); + printf("%u", pagesize); break; case 'c': /* Involuntary context switches. */ printf("%lu", resp->ru.ru_nivcsw); @@ -327,7 +339,7 @@ static void summarize(const char *fmt, char **command, resource_t * resp) printf("%lu", resp->ru.ru_nsignals); break; case 'p': /* Average stack segment. */ - printf("%lu", ptok((UL) resp->ru.ru_isrss) / cpu_ticks); + printf("%lu", ptok(pagesize, (UL) resp->ru.ru_isrss) / cpu_ticks); break; case 'r': /* Incoming socket messages received. */ printf("%lu", resp->ru.ru_msgrcv); @@ -336,7 +348,7 @@ static void summarize(const char *fmt, char **command, resource_t * resp) printf("%lu", resp->ru.ru_msgsnd); break; case 't': /* Average resident set size. */ - printf("%lu", ptok((UL) resp->ru.ru_idrss) / cpu_ticks); + printf("%lu", ptok(pagesize, (UL) resp->ru.ru_idrss) / cpu_ticks); break; case 'w': /* Voluntary context switches. */ printf("%lu", resp->ru.ru_nvcsw); @@ -351,17 +363,17 @@ static void summarize(const char *fmt, char **command, resource_t * resp) case '\\': /* Format escape. */ switch (*++fmt) { default: - putc('\\', stdout); + bb_putchar('\\'); /*FALLTHROUGH*/ case '\\': if (!*fmt) goto ret; - putc(*fmt, stdout); + bb_putchar(*fmt); break; case 't': - putc('\t', stdout); + bb_putchar('\t'); break; case 'n': - putc('\n', stdout); + bb_putchar('\n'); break; } break; @@ -370,82 +382,85 @@ static void summarize(const char *fmt, char **command, resource_t * resp) ++fmt; } /* ret: */ - putc('\n', stdout); + bb_putchar('\n'); } /* Run command CMD and return statistics on it. Put the statistics in *RESP. */ -static void run_command(char *const *cmd, resource_t * resp) +static void run_command(char *const *cmd, resource_t *resp) { - pid_t pid; /* Pid of child. */ - __sighandler_t interrupt_signal, quit_signal; - - resp->elapsed_ms = monotonic_us() / 1000; - pid = vfork(); /* Run CMD as child process. */ - if (pid < 0) - bb_error_msg_and_die("cannot fork"); - else if (pid == 0) { /* If child. */ - /* Don't cast execvp arguments; that causes errors on some systems, - versus merely warnings if the cast is left off. */ - BB_EXECVP(cmd[0], cmd); - bb_error_msg("cannot run %s", cmd[0]); - _exit(errno == ENOENT ? 127 : 126); + pid_t pid; + void (*interrupt_signal)(int); + void (*quit_signal)(int); + + resp->elapsed_ms = monotonic_ms(); + pid = xvfork(); + if (pid == 0) { + /* Child */ + BB_EXECVP_or_die((char**)cmd); } /* Have signals kill the child but not self (if possible). */ +//TODO: just block all sigs? and re-enable them in the very end in main? interrupt_signal = signal(SIGINT, SIG_IGN); quit_signal = signal(SIGQUIT, SIG_IGN); - if (resuse_end(pid, resp) == 0) - bb_error_msg("error waiting for child process"); + resuse_end(pid, resp); /* Re-enable signals. */ signal(SIGINT, interrupt_signal); signal(SIGQUIT, quit_signal); } -int time_main(int argc, char **argv); -int time_main(int argc, char **argv) +int time_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; +int time_main(int argc UNUSED_PARAM, char **argv) { resource_t res; - const char *output_format = default_format; - char c; - - goto next; - /* Parse any options -- don't use getopt() here so we don't - * consume the args of our client application... */ - while (argc > 0 && argv[0][0] == '-') { - while ((c = *++*argv)) { - switch (c) { - case 'v': - output_format = long_format; - break; - case 'p': - output_format = posix_format; - break; - default: - bb_show_usage(); - } - } - next: - argv++; - argc--; - if (!argc) - bb_show_usage(); + /* $TIME has lowest prio (-v,-p,-f FMT overrride it) */ + const char *output_format = getenv("TIME") ? : default_format; + char *output_filename; + int output_fd; + int opt; + int ex; + enum { + OPT_v = (1 << 0), + OPT_p = (1 << 1), + OPT_a = (1 << 2), + OPT_o = (1 << 3), + OPT_f = (1 << 4), + }; + + /* "+": stop on first non-option */ + opt = getopt32(argv, "^+" "vpao:f:" "\0" "-1"/*at least one arg*/, + &output_filename, &output_format + ); + argv += optind; + if (opt & OPT_v) + output_format = long_format; + if (opt & OPT_p) + output_format = posix_format; + output_fd = STDERR_FILENO; + if (opt & OPT_o) { + output_fd = xopen(output_filename, + (opt & OPT_a) /* append? */ + ? (O_CREAT | O_WRONLY | O_CLOEXEC | O_APPEND) + : (O_CREAT | O_WRONLY | O_CLOEXEC | O_TRUNC) + ); } run_command(argv, &res); /* Cheat. printf's are shorter :) */ - stdout = stderr; - dup2(2, 1); /* just in case libc does something silly :( */ + xdup2(output_fd, STDOUT_FILENO); summarize(output_format, argv, &res); + ex = WEXITSTATUS(res.waitstatus); + /* Impossible: we do not use WUNTRACED flag in wait()... if (WIFSTOPPED(res.waitstatus)) - return WSTOPSIG(res.waitstatus); + ex = WSTOPSIG(res.waitstatus); + */ if (WIFSIGNALED(res.waitstatus)) - return WTERMSIG(res.waitstatus); - if (WIFEXITED(res.waitstatus)) - return WEXITSTATUS(res.waitstatus); - fflush_stdout_and_exit(0); + ex = WTERMSIG(res.waitstatus); + + fflush_stdout_and_exit(ex); }