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