Audit time(1)

1) fix usage().
2) sort includes and comment properly. rename rbeg and rend to r0 and r1.
3) argc style and usage fixes.
4) make error-messages clearer.
5) BUGFIX: It was ignored when fork() failed.
6) Don't call enprintf() after execvp and use _exit instead.
This commit is contained in:
FRIGN 2015-03-05 00:23:09 +01:00
parent a443014e94
commit 1250a8962f
1 changed files with 22 additions and 15 deletions

37
time.c
View File

@ -11,17 +11,17 @@
static void static void
usage(void) usage(void)
{ {
eprintf("usage: %s [-p] utility [argument ...]\n", argv0); eprintf("usage: %s [-p] cmd [arg ...]\n", argv0);
} }
int int
main(int argc, char *argv[]) main(int argc, char *argv[])
{ {
pid_t pid; pid_t pid;
struct tms tms; /* hold user and sys times */ struct tms tms; /* user and sys times */
clock_t rbeg, rend; /* real time */ clock_t r0, r1; /* real time */
long ticks; /* per second */ long ticks; /* per second */
int status; int status, savederrno;
ARGBEGIN { ARGBEGIN {
case 'p': case 'p':
@ -30,26 +30,33 @@ main(int argc, char *argv[])
usage(); usage();
} ARGEND; } ARGEND;
if (!*argv) if (!argc)
usage(); usage();
if ((ticks = sysconf(_SC_CLK_TCK)) <= 0) if ((ticks = sysconf(_SC_CLK_TCK)) <= 0)
eprintf("sysconf() failed to retrieve clock ticks per second\n"); eprintf("sysconf _SC_CLK_TCK:");
if ((rbeg = times(&tms)) < 0) if ((r0 = times(&tms)) < 0)
eprintf("times() failed to retrieve start times:"); eprintf("times:");
if (!(pid = fork())) { /* child */ switch ((pid = fork())) {
execvp(*argv, argv); case -1:
enprintf(errno == ENOENT ? 127 : 126, "failed to exec %s:", *argv); eprintf("fork:");
case 0:
execvp(argv[0], argv);
savederrno = errno;
weprintf("exec %s:", argv[0]);
_exit(126 + (savederrno == ENOENT));
default:
break;
} }
waitpid(pid, &status, 0); waitpid(pid, &status, 0);
if ((rend = times(&tms)) < 0) if ((r1 = times(&tms)) < 0)
eprintf("times() failed to retrieve end times:"); eprintf("times:");
fprintf(stderr, "real %f\nuser %f\nsys %f\n", fprintf(stderr, "real %f\nuser %f\nsys %f\n",
(rend - rbeg) / (double)ticks, (r1 - r0) / (double)ticks,
tms.tms_cutime / (double)ticks, tms.tms_cutime / (double)ticks,
tms.tms_cstime / (double)ticks); tms.tms_cstime / (double)ticks);