xref: /freebsd/usr.bin/time/time.c (revision 83823d063ab57db8d3954c1530d036f1ccdceb41)
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 #endif /* not lint */
43 
44 #include <sys/types.h>
45 #include <sys/resource.h>
46 #include <sys/signal.h>
47 #include <sys/sysctl.h>
48 #include <sys/time.h>
49 #include <sys/wait.h>
50 
51 #include <err.h>
52 #include <errno.h>
53 #include <locale.h>
54 #include <signal.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <stdint.h>
58 #include <string.h>
59 #include <time.h>
60 #include <unistd.h>
61 
62 static int getstathz(void);
63 static void humantime(FILE *, long, long);
64 static void showtime(FILE *, struct timespec *, struct timespec *,
65     struct rusage *);
66 static void siginfo(int);
67 static void usage(void) __dead2;
68 
69 static sig_atomic_t siginfo_recvd;
70 static char decimal_point;
71 static struct timespec before_ts;
72 static int hflag, pflag;
73 
74 int
75 main(int argc, char **argv)
76 {
77 	int aflag, ch, lflag, status;
78 	int exitonsig;
79 	pid_t pid;
80 	struct rlimit rl;
81 	struct rusage ru;
82 	struct timespec after;
83 	char *ofn = NULL;
84 	FILE *out = stderr;
85 
86 	(void) setlocale(LC_NUMERIC, "");
87 	decimal_point = localeconv()->decimal_point[0];
88 
89 	aflag = hflag = lflag = pflag = 0;
90 	while ((ch = getopt(argc, argv, "ahlo:p")) != -1)
91 		switch((char)ch) {
92 		case 'a':
93 			aflag = 1;
94 			break;
95 		case 'h':
96 			hflag = 1;
97 			break;
98 		case 'l':
99 			lflag = 1;
100 			break;
101 		case 'o':
102 			ofn = optarg;
103 			break;
104 		case 'p':
105 			pflag = 1;
106 			break;
107 		case '?':
108 		default:
109 			usage();
110 		}
111 
112 	if (!(argc -= optind))
113 		exit(0);
114 	argv += optind;
115 
116 	if (ofn) {
117 	        if ((out = fopen(ofn, aflag ? "ae" : "we")) == NULL)
118 		        err(1, "%s", ofn);
119 		setvbuf(out, (char *)NULL, _IONBF, (size_t)0);
120 	}
121 
122 	if (clock_gettime(CLOCK_MONOTONIC, &before_ts))
123 		err(1, "clock_gettime");
124 	switch(pid = fork()) {
125 	case -1:			/* error */
126 		err(1, "time");
127 		/* NOTREACHED */
128 	case 0:				/* child */
129 		execvp(*argv, argv);
130 		err(errno == ENOENT ? 127 : 126, "%s", *argv);
131 		/* NOTREACHED */
132 	}
133 	/* parent */
134 	(void)signal(SIGINT, SIG_IGN);
135 	(void)signal(SIGQUIT, SIG_IGN);
136 	siginfo_recvd = 0;
137 	(void)signal(SIGINFO, siginfo);
138 	(void)siginterrupt(SIGINFO, 1);
139 	while (wait4(pid, &status, 0, &ru) != pid) {
140 		if (siginfo_recvd) {
141 			siginfo_recvd = 0;
142 			if (clock_gettime(CLOCK_MONOTONIC, &after))
143 				err(1, "clock_gettime");
144 			getrusage(RUSAGE_CHILDREN, &ru);
145 			showtime(stdout, &before_ts, &after, &ru);
146 		}
147 	}
148 	if (clock_gettime(CLOCK_MONOTONIC, &after))
149 		err(1, "clock_gettime");
150 	if ( ! WIFEXITED(status))
151 		warnx("command terminated abnormally");
152 	exitonsig = WIFSIGNALED(status) ? WTERMSIG(status) : 0;
153 	showtime(out, &before_ts, &after, &ru);
154 	if (lflag) {
155 		int hz = getstathz();
156 		u_long ticks;
157 
158 		ticks = hz * (ru.ru_utime.tv_sec + ru.ru_stime.tv_sec) +
159 		     hz * (ru.ru_utime.tv_usec + ru.ru_stime.tv_usec) / 1000000;
160 
161 		/*
162 		 * If our round-off on the tick calculation still puts us at 0,
163 		 * then always assume at least one tick.
164 		 */
165 		if (ticks == 0)
166 			ticks = 1;
167 
168 		fprintf(out, "%10ld  %s\n",
169 			ru.ru_maxrss, "maximum resident set size");
170 		fprintf(out, "%10ld  %s\n",
171 			ru.ru_ixrss / ticks, "average shared memory size");
172 		fprintf(out, "%10ld  %s\n",
173 			ru.ru_idrss / ticks, "average unshared data size");
174 		fprintf(out, "%10ld  %s\n",
175 			ru.ru_isrss / ticks, "average unshared stack size");
176 		fprintf(out, "%10ld  %s\n",
177 			ru.ru_minflt, "page reclaims");
178 		fprintf(out, "%10ld  %s\n",
179 			ru.ru_majflt, "page faults");
180 		fprintf(out, "%10ld  %s\n",
181 			ru.ru_nswap, "swaps");
182 		fprintf(out, "%10ld  %s\n",
183 			ru.ru_inblock, "block input operations");
184 		fprintf(out, "%10ld  %s\n",
185 			ru.ru_oublock, "block output operations");
186 		fprintf(out, "%10ld  %s\n",
187 			ru.ru_msgsnd, "messages sent");
188 		fprintf(out, "%10ld  %s\n",
189 			ru.ru_msgrcv, "messages received");
190 		fprintf(out, "%10ld  %s\n",
191 			ru.ru_nsignals, "signals received");
192 		fprintf(out, "%10ld  %s\n",
193 			ru.ru_nvcsw, "voluntary context switches");
194 		fprintf(out, "%10ld  %s\n",
195 			ru.ru_nivcsw, "involuntary context switches");
196 	}
197 	/*
198 	 * If the child has exited on a signal, exit on the same
199 	 * signal, too, in order to reproduce the child's exit status.
200 	 * However, avoid actually dumping core from the current process.
201 	 */
202 	if (exitonsig) {
203 		if (signal(exitonsig, SIG_DFL) == SIG_ERR)
204 			warn("signal");
205 		else {
206 			rl.rlim_max = rl.rlim_cur = 0;
207 			if (setrlimit(RLIMIT_CORE, &rl) == -1)
208 				warn("setrlimit");
209 			kill(getpid(), exitonsig);
210 		}
211 	}
212 	exit (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE);
213 }
214 
215 static void
216 usage(void)
217 {
218 	fprintf(stderr,
219 	    "usage: time [-al] [-h | -p] [-o file] utility [argument ...]\n");
220 	exit(1);
221 }
222 
223 /*
224  * Return the frequency of the kernel's statistics clock.
225  */
226 static int
227 getstathz(void)
228 {
229 	int mib[2];
230 	size_t size;
231 	struct clockinfo clockrate;
232 
233 	mib[0] = CTL_KERN;
234 	mib[1] = KERN_CLOCKRATE;
235 	size = sizeof clockrate;
236 	if (sysctl(mib, 2, &clockrate, &size, NULL, 0) == -1)
237 		err(1, "sysctl kern.clockrate");
238 	return clockrate.stathz;
239 }
240 
241 static void
242 humantime(FILE *out, long sec, long centisec)
243 {
244 	long days, hrs, mins;
245 
246 	days = sec / (60L * 60 * 24);
247 	sec %= (60L * 60 * 24);
248 	hrs = sec / (60L * 60);
249 	sec %= (60L * 60);
250 	mins = sec / 60;
251 	sec %= 60;
252 
253 	fprintf(out, "\t");
254 	if (days)
255 		fprintf(out, "%ldd", days);
256 	if (hrs)
257 		fprintf(out, "%ldh", hrs);
258 	if (mins)
259 		fprintf(out, "%ldm", mins);
260 	fprintf(out, "%ld%c%02lds", sec, decimal_point, centisec);
261 }
262 
263 static void
264 showtime(FILE *out, struct timespec *before, struct timespec *after,
265     struct rusage *ru)
266 {
267 
268 	after->tv_sec -= before->tv_sec;
269 	after->tv_nsec -= before->tv_nsec;
270 	if (after->tv_nsec < 0)
271 		after->tv_sec--, after->tv_nsec += 1000000000;
272 
273 	if (pflag) {
274 		/* POSIX wants output that must look like
275 		"real %f\nuser %f\nsys %f\n" and requires
276 		at least two digits after the radix. */
277 		fprintf(out, "real %jd%c%02ld\n",
278 			(intmax_t)after->tv_sec, decimal_point,
279 			after->tv_nsec/10000000);
280 		fprintf(out, "user %jd%c%02ld\n",
281 			(intmax_t)ru->ru_utime.tv_sec, decimal_point,
282 			ru->ru_utime.tv_usec/10000);
283 		fprintf(out, "sys %jd%c%02ld\n",
284 			(intmax_t)ru->ru_stime.tv_sec, decimal_point,
285 			ru->ru_stime.tv_usec/10000);
286 	} else if (hflag) {
287 		humantime(out, after->tv_sec, after->tv_nsec/10000000);
288 		fprintf(out, " real\t");
289 		humantime(out, ru->ru_utime.tv_sec, ru->ru_utime.tv_usec/10000);
290 		fprintf(out, " user\t");
291 		humantime(out, ru->ru_stime.tv_sec, ru->ru_stime.tv_usec/10000);
292 		fprintf(out, " sys\n");
293 	} else {
294 		fprintf(out, "%9jd%c%02ld real ",
295 			(intmax_t)after->tv_sec, decimal_point,
296 			after->tv_nsec/10000000);
297 		fprintf(out, "%9jd%c%02ld user ",
298 			(intmax_t)ru->ru_utime.tv_sec, decimal_point,
299 			ru->ru_utime.tv_usec/10000);
300 		fprintf(out, "%9jd%c%02ld sys\n",
301 			(intmax_t)ru->ru_stime.tv_sec, decimal_point,
302 			ru->ru_stime.tv_usec/10000);
303 	}
304 }
305 
306 static void
307 siginfo(int sig __unused)
308 {
309 
310 	siginfo_recvd = 1;
311 }
312