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