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