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