xref: /freebsd/usr.bin/time/time.c (revision ba3c1f5972d7b90feb6e6da47905ff2757e0fe57)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1987, 1988, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1987, 1988, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n";
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)time.c	8.1 (Berkeley) 6/6/93";
41 #endif
42 static const char rcsid[] =
43   "$FreeBSD$";
44 #endif /* not lint */
45 
46 #include <sys/types.h>
47 #include <sys/resource.h>
48 #include <sys/signal.h>
49 #include <sys/sysctl.h>
50 #include <sys/time.h>
51 #include <sys/wait.h>
52 
53 #include <err.h>
54 #include <errno.h>
55 #include <locale.h>
56 #include <signal.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <stdint.h>
60 #include <string.h>
61 #include <time.h>
62 #include <unistd.h>
63 
64 static int getstathz(void);
65 static void humantime(FILE *, long, long);
66 static void showtime(FILE *, struct timespec *, struct timespec *,
67     struct rusage *);
68 static void siginfo(int);
69 static void usage(void) __dead2;
70 
71 static sig_atomic_t siginfo_recvd;
72 static char decimal_point;
73 static struct timespec before_ts;
74 static int hflag, pflag;
75 
76 int
77 main(int argc, char **argv)
78 {
79 	int aflag, ch, lflag, status;
80 	int exitonsig;
81 	pid_t pid;
82 	struct rlimit rl;
83 	struct rusage ru;
84 	struct timespec after;
85 	char *ofn = NULL;
86 	FILE *out = stderr;
87 
88 	(void) setlocale(LC_NUMERIC, "");
89 	decimal_point = localeconv()->decimal_point[0];
90 
91 	aflag = hflag = lflag = pflag = 0;
92 	while ((ch = getopt(argc, argv, "ahlo:p")) != -1)
93 		switch((char)ch) {
94 		case 'a':
95 			aflag = 1;
96 			break;
97 		case 'h':
98 			hflag = 1;
99 			break;
100 		case 'l':
101 			lflag = 1;
102 			break;
103 		case 'o':
104 			ofn = optarg;
105 			break;
106 		case 'p':
107 			pflag = 1;
108 			break;
109 		case '?':
110 		default:
111 			usage();
112 		}
113 
114 	if (!(argc -= optind))
115 		exit(0);
116 	argv += optind;
117 
118 	if (ofn) {
119 	        if ((out = fopen(ofn, aflag ? "ae" : "we")) == NULL)
120 		        err(1, "%s", ofn);
121 		setvbuf(out, (char *)NULL, _IONBF, (size_t)0);
122 	}
123 
124 	if (clock_gettime(CLOCK_MONOTONIC, &before_ts))
125 		err(1, "clock_gettime");
126 	switch(pid = fork()) {
127 	case -1:			/* error */
128 		err(1, "time");
129 		/* NOTREACHED */
130 	case 0:				/* child */
131 		execvp(*argv, argv);
132 		err(errno == ENOENT ? 127 : 126, "%s", *argv);
133 		/* NOTREACHED */
134 	}
135 	/* parent */
136 	(void)signal(SIGINT, SIG_IGN);
137 	(void)signal(SIGQUIT, SIG_IGN);
138 	siginfo_recvd = 0;
139 	(void)signal(SIGINFO, siginfo);
140 	(void)siginterrupt(SIGINFO, 1);
141 	while (wait4(pid, &status, 0, &ru) != pid) {
142 		if (siginfo_recvd) {
143 			siginfo_recvd = 0;
144 			if (clock_gettime(CLOCK_MONOTONIC, &after))
145 				err(1, "clock_gettime");
146 			getrusage(RUSAGE_CHILDREN, &ru);
147 			showtime(stdout, &before_ts, &after, &ru);
148 		}
149 	}
150 	if (clock_gettime(CLOCK_MONOTONIC, &after))
151 		err(1, "clock_gettime");
152 	if ( ! WIFEXITED(status))
153 		warnx("command terminated abnormally");
154 	exitonsig = WIFSIGNALED(status) ? WTERMSIG(status) : 0;
155 	showtime(out, &before_ts, &after, &ru);
156 	if (lflag) {
157 		int hz = getstathz();
158 		u_long ticks;
159 
160 		ticks = hz * (ru.ru_utime.tv_sec + ru.ru_stime.tv_sec) +
161 		     hz * (ru.ru_utime.tv_usec + ru.ru_stime.tv_usec) / 1000000;
162 
163 		/*
164 		 * If our round-off on the tick calculation still puts us at 0,
165 		 * then always assume at least one tick.
166 		 */
167 		if (ticks == 0)
168 			ticks = 1;
169 
170 		fprintf(out, "%10ld  %s\n",
171 			ru.ru_maxrss, "maximum resident set size");
172 		fprintf(out, "%10ld  %s\n",
173 			ru.ru_ixrss / ticks, "average shared memory size");
174 		fprintf(out, "%10ld  %s\n",
175 			ru.ru_idrss / ticks, "average unshared data size");
176 		fprintf(out, "%10ld  %s\n",
177 			ru.ru_isrss / ticks, "average unshared stack size");
178 		fprintf(out, "%10ld  %s\n",
179 			ru.ru_minflt, "page reclaims");
180 		fprintf(out, "%10ld  %s\n",
181 			ru.ru_majflt, "page faults");
182 		fprintf(out, "%10ld  %s\n",
183 			ru.ru_nswap, "swaps");
184 		fprintf(out, "%10ld  %s\n",
185 			ru.ru_inblock, "block input operations");
186 		fprintf(out, "%10ld  %s\n",
187 			ru.ru_oublock, "block output operations");
188 		fprintf(out, "%10ld  %s\n",
189 			ru.ru_msgsnd, "messages sent");
190 		fprintf(out, "%10ld  %s\n",
191 			ru.ru_msgrcv, "messages received");
192 		fprintf(out, "%10ld  %s\n",
193 			ru.ru_nsignals, "signals received");
194 		fprintf(out, "%10ld  %s\n",
195 			ru.ru_nvcsw, "voluntary context switches");
196 		fprintf(out, "%10ld  %s\n",
197 			ru.ru_nivcsw, "involuntary context switches");
198 	}
199 	/*
200 	 * If the child has exited on a signal, exit on the same
201 	 * signal, too, in order to reproduce the child's exit status.
202 	 * However, avoid actually dumping core from the current process.
203 	 */
204 	if (exitonsig) {
205 		if (signal(exitonsig, SIG_DFL) == SIG_ERR)
206 			warn("signal");
207 		else {
208 			rl.rlim_max = rl.rlim_cur = 0;
209 			if (setrlimit(RLIMIT_CORE, &rl) == -1)
210 				warn("setrlimit");
211 			kill(getpid(), exitonsig);
212 		}
213 	}
214 	exit (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE);
215 }
216 
217 static void
218 usage(void)
219 {
220 	fprintf(stderr,
221 	    "usage: time [-al] [-h | -p] [-o file] utility [argument ...]\n");
222 	exit(1);
223 }
224 
225 /*
226  * Return the frequency of the kernel's statistics clock.
227  */
228 static int
229 getstathz(void)
230 {
231 	int mib[2];
232 	size_t size;
233 	struct clockinfo clockrate;
234 
235 	mib[0] = CTL_KERN;
236 	mib[1] = KERN_CLOCKRATE;
237 	size = sizeof clockrate;
238 	if (sysctl(mib, 2, &clockrate, &size, NULL, 0) == -1)
239 		err(1, "sysctl kern.clockrate");
240 	return clockrate.stathz;
241 }
242 
243 static void
244 humantime(FILE *out, long sec, long centisec)
245 {
246 	long days, hrs, mins;
247 
248 	days = sec / (60L * 60 * 24);
249 	sec %= (60L * 60 * 24);
250 	hrs = sec / (60L * 60);
251 	sec %= (60L * 60);
252 	mins = sec / 60;
253 	sec %= 60;
254 
255 	fprintf(out, "\t");
256 	if (days)
257 		fprintf(out, "%ldd", days);
258 	if (hrs)
259 		fprintf(out, "%ldh", hrs);
260 	if (mins)
261 		fprintf(out, "%ldm", mins);
262 	fprintf(out, "%ld%c%02lds", sec, decimal_point, centisec);
263 }
264 
265 static void
266 showtime(FILE *out, struct timespec *before, struct timespec *after,
267     struct rusage *ru)
268 {
269 
270 	after->tv_sec -= before->tv_sec;
271 	after->tv_nsec -= before->tv_nsec;
272 	if (after->tv_nsec < 0)
273 		after->tv_sec--, after->tv_nsec += 1000000000;
274 
275 	if (pflag) {
276 		/* POSIX wants output that must look like
277 		"real %f\nuser %f\nsys %f\n" and requires
278 		at least two digits after the radix. */
279 		fprintf(out, "real %jd%c%02ld\n",
280 			(intmax_t)after->tv_sec, decimal_point,
281 			after->tv_nsec/10000000);
282 		fprintf(out, "user %jd%c%02ld\n",
283 			(intmax_t)ru->ru_utime.tv_sec, decimal_point,
284 			ru->ru_utime.tv_usec/10000);
285 		fprintf(out, "sys %jd%c%02ld\n",
286 			(intmax_t)ru->ru_stime.tv_sec, decimal_point,
287 			ru->ru_stime.tv_usec/10000);
288 	} else if (hflag) {
289 		humantime(out, after->tv_sec, after->tv_nsec/10000000);
290 		fprintf(out, " real\t");
291 		humantime(out, ru->ru_utime.tv_sec, ru->ru_utime.tv_usec/10000);
292 		fprintf(out, " user\t");
293 		humantime(out, ru->ru_stime.tv_sec, ru->ru_stime.tv_usec/10000);
294 		fprintf(out, " sys\n");
295 	} else {
296 		fprintf(out, "%9jd%c%02ld real ",
297 			(intmax_t)after->tv_sec, decimal_point,
298 			after->tv_nsec/10000000);
299 		fprintf(out, "%9jd%c%02ld user ",
300 			(intmax_t)ru->ru_utime.tv_sec, decimal_point,
301 			ru->ru_utime.tv_usec/10000);
302 		fprintf(out, "%9jd%c%02ld sys\n",
303 			(intmax_t)ru->ru_stime.tv_sec, decimal_point,
304 			ru->ru_stime.tv_usec/10000);
305 	}
306 }
307 
308 static void
309 siginfo(int sig __unused)
310 {
311 
312 	siginfo_recvd = 1;
313 }
314