xref: /freebsd/usr.bin/time/time.c (revision 4fd2d3b6927878771635a3628ae1623daf810d39)
1 /*
2  * Copyright (c) 1987, 1988, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1987, 1988, 1993\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)time.c	8.1 (Berkeley) 6/6/93";
43 #endif
44 static const char rcsid[] =
45   "$FreeBSD$";
46 #endif /* not lint */
47 
48 #include <sys/types.h>
49 #include <sys/resource.h>
50 #include <sys/signal.h>
51 #include <sys/sysctl.h>
52 #include <sys/time.h>
53 #include <sys/wait.h>
54 
55 #include <err.h>
56 #include <errno.h>
57 #include <locale.h>
58 #include <signal.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <stdint.h>
62 #include <string.h>
63 #include <unistd.h>
64 
65 static int getstathz(void);
66 static void humantime(FILE *, long, long);
67 static void showtime(FILE *, struct timeval *, struct timeval *,
68     struct rusage *);
69 static void siginfo(int);
70 static void usage(void);
71 
72 static char decimal_point;
73 static struct timeval before_tv;
74 static int hflag, pflag;
75 
76 int
77 main(int argc, char **argv)
78 {
79 	int aflag, ch, lflag, status;
80 	int exitonsig;
81 	pid_t pid;
82 	struct rlimit rl;
83 	struct rusage ru;
84 	struct timeval after;
85 	char *ofn = NULL;
86 	FILE *out = stderr;
87 
88 	(void) setlocale(LC_NUMERIC, "");
89 	decimal_point = localeconv()->decimal_point[0];
90 
91 	aflag = hflag = lflag = pflag = 0;
92 	while ((ch = getopt(argc, argv, "ahlo:p")) != -1)
93 		switch((char)ch) {
94 		case 'a':
95 			aflag = 1;
96 			break;
97 		case 'h':
98 			hflag = 1;
99 			break;
100 		case 'l':
101 			lflag = 1;
102 			break;
103 		case 'o':
104 			ofn = optarg;
105 			break;
106 		case 'p':
107 			pflag = 1;
108 			break;
109 		case '?':
110 		default:
111 			usage();
112 		}
113 
114 	if (!(argc -= optind))
115 		exit(0);
116 	argv += optind;
117 
118 	if (ofn) {
119 	        if ((out = fopen(ofn, aflag ? "a" : "w")) == NULL)
120 		        err(1, "%s", ofn);
121 		setvbuf(out, (char *)NULL, _IONBF, (size_t)0);
122 	}
123 
124 	gettimeofday(&before_tv, (struct timezone *)NULL);
125 	switch(pid = fork()) {
126 	case -1:			/* error */
127 		err(1, "time");
128 		/* NOTREACHED */
129 	case 0:				/* child */
130 		if (ofn)
131 			fclose(out);
132 		execvp(*argv, argv);
133 		err(errno == ENOENT ? 127 : 126, "%s", *argv);
134 		/* NOTREACHED */
135 	}
136 	/* parent */
137 	(void)signal(SIGINT, SIG_IGN);
138 	(void)signal(SIGQUIT, SIG_IGN);
139 	(void)signal(SIGINFO, siginfo);
140 	while (wait4(pid, &status, 0, &ru) != pid);
141 	gettimeofday(&after, (struct timezone *)NULL);
142 	if ( ! WIFEXITED(status))
143 		warnx("command terminated abnormally");
144 	exitonsig = WIFSIGNALED(status) ? WTERMSIG(status) : 0;
145 	showtime(out, &before_tv, &after, &ru);
146 	if (lflag) {
147 		int hz = getstathz();
148 		u_long ticks;
149 
150 		ticks = hz * (ru.ru_utime.tv_sec + ru.ru_stime.tv_sec) +
151 		     hz * (ru.ru_utime.tv_usec + ru.ru_stime.tv_usec) / 1000000;
152 
153 		/*
154 		 * If our round-off on the tick calculation still puts us at 0,
155 		 * then always assume at least one tick.
156 		 */
157 		if (ticks == 0)
158 			ticks = 1;
159 
160 		fprintf(out, "%10ld  %s\n",
161 			ru.ru_maxrss, "maximum resident set size");
162 		fprintf(out, "%10ld  %s\n",
163 			ru.ru_ixrss / ticks, "average shared memory size");
164 		fprintf(out, "%10ld  %s\n",
165 			ru.ru_idrss / ticks, "average unshared data size");
166 		fprintf(out, "%10ld  %s\n",
167 			ru.ru_isrss / ticks, "average unshared stack size");
168 		fprintf(out, "%10ld  %s\n",
169 			ru.ru_minflt, "page reclaims");
170 		fprintf(out, "%10ld  %s\n",
171 			ru.ru_majflt, "page faults");
172 		fprintf(out, "%10ld  %s\n",
173 			ru.ru_nswap, "swaps");
174 		fprintf(out, "%10ld  %s\n",
175 			ru.ru_inblock, "block input operations");
176 		fprintf(out, "%10ld  %s\n",
177 			ru.ru_oublock, "block output operations");
178 		fprintf(out, "%10ld  %s\n",
179 			ru.ru_msgsnd, "messages sent");
180 		fprintf(out, "%10ld  %s\n",
181 			ru.ru_msgrcv, "messages received");
182 		fprintf(out, "%10ld  %s\n",
183 			ru.ru_nsignals, "signals received");
184 		fprintf(out, "%10ld  %s\n",
185 			ru.ru_nvcsw, "voluntary context switches");
186 		fprintf(out, "%10ld  %s\n",
187 			ru.ru_nivcsw, "involuntary context switches");
188 	}
189 	/*
190 	 * If the child has exited on a signal, exit on the same
191 	 * signal, too, in order to reproduce the child's exit status.
192 	 * However, avoid actually dumping core from the current process.
193 	 */
194 	if (exitonsig) {
195 		if (signal(exitonsig, SIG_DFL) == SIG_ERR)
196 			warn("signal");
197 		else {
198 			rl.rlim_max = rl.rlim_cur = 0;
199 			if (setrlimit(RLIMIT_CORE, &rl) == -1)
200 				warn("setrlimit");
201 			kill(getpid(), exitonsig);
202 		}
203 	}
204 	exit (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE);
205 }
206 
207 static void
208 usage(void)
209 {
210 	fprintf(stderr,
211 	    "usage: time [-al] [-h | -p] [-o file] utility [argument ...]\n");
212 	exit(1);
213 }
214 
215 /*
216  * Return the frequency of the kernel's statistics clock.
217  */
218 static int
219 getstathz(void)
220 {
221 	int mib[2];
222 	size_t size;
223 	struct clockinfo clockrate;
224 
225 	mib[0] = CTL_KERN;
226 	mib[1] = KERN_CLOCKRATE;
227 	size = sizeof clockrate;
228 	if (sysctl(mib, 2, &clockrate, &size, NULL, 0) == -1)
229 		err(1, "sysctl kern.clockrate");
230 	return clockrate.stathz;
231 }
232 
233 static void
234 humantime(FILE *out, long sec, long usec)
235 {
236 	long days, hrs, mins;
237 
238 	days = sec / (60L * 60 * 24);
239 	sec %= (60L * 60 * 24);
240 	hrs = sec / (60L * 60);
241 	sec %= (60L * 60);
242 	mins = sec / 60;
243 	sec %= 60;
244 
245 	fprintf(out, "\t");
246 	if (days)
247 		fprintf(out, "%ldd", days);
248 	if (hrs)
249 		fprintf(out, "%ldh", hrs);
250 	if (mins)
251 		fprintf(out, "%ldm", mins);
252 	fprintf(out, "%ld%c%02lds", sec, decimal_point, usec);
253 }
254 
255 static void
256 showtime(FILE *out, struct timeval *before, struct timeval *after,
257     struct rusage *ru)
258 {
259 
260 	after->tv_sec -= before->tv_sec;
261 	after->tv_usec -= before->tv_usec;
262 	if (after->tv_usec < 0)
263 		after->tv_sec--, after->tv_usec += 1000000;
264 
265 	if (pflag) {
266 		/* POSIX wants output that must look like
267 		"real %f\nuser %f\nsys %f\n" and requires
268 		at least two digits after the radix. */
269 		fprintf(out, "real %jd%c%02ld\n",
270 			(intmax_t)after->tv_sec, decimal_point,
271 			after->tv_usec/10000);
272 		fprintf(out, "user %jd%c%02ld\n",
273 			(intmax_t)ru->ru_utime.tv_sec, decimal_point,
274 			ru->ru_utime.tv_usec/10000);
275 		fprintf(out, "sys %jd%c%02ld\n",
276 			(intmax_t)ru->ru_stime.tv_sec, decimal_point,
277 			ru->ru_stime.tv_usec/10000);
278 	} else if (hflag) {
279 		humantime(out, after->tv_sec, after->tv_usec/10000);
280 		fprintf(out, " real\t");
281 		humantime(out, ru->ru_utime.tv_sec, ru->ru_utime.tv_usec/10000);
282 		fprintf(out, " user\t");
283 		humantime(out, ru->ru_stime.tv_sec, ru->ru_stime.tv_usec/10000);
284 		fprintf(out, " sys\n");
285 	} else {
286 		fprintf(out, "%9jd%c%02ld real ",
287 			(intmax_t)after->tv_sec, decimal_point,
288 			after->tv_usec/10000);
289 		fprintf(out, "%9jd%c%02ld user ",
290 			(intmax_t)ru->ru_utime.tv_sec, decimal_point,
291 			ru->ru_utime.tv_usec/10000);
292 		fprintf(out, "%9jd%c%02ld sys\n",
293 			(intmax_t)ru->ru_stime.tv_sec, decimal_point,
294 			ru->ru_stime.tv_usec/10000);
295 	}
296 }
297 
298 static void
299 siginfo(int sig __unused)
300 {
301 	struct timeval after;
302 	struct rusage ru;
303 
304 	gettimeofday(&after, (struct timezone *)NULL);
305 	getrusage(RUSAGE_CHILDREN, &ru);
306 	showtime(stdout, &before_tv, &after, &ru);
307 }
308