xref: /plan9-contrib/sys/src/cmd/time.c (revision 219b2ee8daee37f4aad58d63f21287faa8e4ffdc)
1 #include <u.h>
2 #include <libc.h>
3 
4 char	output[4096];
5 void	add(char*, ...);
6 void	error(char*);
7 void	notifyf(void*, char*);
8 
9 void
10 main(int argc, char *argv[])
11 {
12 	int i;
13 	Waitmsg w;
14 	long l;
15 	char *p;
16 	char err[ERRLEN];
17 
18 	if(argc <= 1){
19 		fprint(2, "usage: time command\n");
20 		exits("usage");
21 	}
22 
23 	switch(fork()){
24 	case -1:
25 		error("fork");
26 	case 0:
27 		exec(argv[1], &argv[1]);
28 		if(argv[1][0] != '/' && strncmp(argv[1], "./", 2) &&
29 		   strncmp(argv[1], "../", 3)){
30 			sprint(output, "/bin/%s", argv[1]);
31 			exec(output, &argv[1]);
32 		}
33 		error(argv[1]);
34 	}
35 
36 	notify(notifyf);
37 
38     loop:
39 	i = wait(&w);
40 	if(i == -1){
41 		errstr(err);
42 		if(strcmp(err, "interrupted") == 0)
43 			goto loop;
44 		error("wait");
45 	}
46 	l = atoi(&w.time[0*12]);
47 	add("%ld.%.2ldu", l/1000, (l%1000)/10);
48 	l = atoi(&w.time[1*12]);
49 	add("%ld.%.2lds", l/1000, (l%1000)/10);
50 	l = atoi(&w.time[2*12]);
51 	add("%ld.%.2ldr", l/1000, (l%1000)/10);
52 	add("\t");
53 	for(i=1; i<argc; i++){
54 		add("%s", argv[i], 0);
55 		if(i>4){
56 			add("...");
57 			break;
58 		}
59 	}
60 	if(w.msg[0]){
61 		p = utfrune(w.msg, ':');
62 		if(p && p[1])
63 			p++;
64 		else
65 			p = w.msg;
66 		add(" # status=%s", p);
67 	}
68 	fprint(2, "%s\n", output);
69 	exits(w.msg);
70 }
71 
72 void
73 add(char *a, ...)
74 {
75 	static beenhere=0;
76 
77 	if(beenhere)
78 		strcat(output, " ");
79 	doprint(output+strlen(output), output+sizeof(output), a, (&a)+1);
80 	beenhere++;
81 }
82 
83 void
84 error(char *s)
85 {
86 	char buf[ERRLEN];
87 
88 	errstr(buf);
89 	fprint(2, "time: %s: %s\n", s, buf);
90 	exits(s);
91 }
92 
93 void
94 notifyf(void *a, char *s)
95 {
96 	USED(a);
97 	if(strcmp(s, "interrupt") == 0)
98 		noted(NCONT);
99 	noted(NDFLT);
100 }
101