xref: /plan9/sys/src/cmd/time.c (revision 9a747e4fd48b9f4522c70c07e8f882a15030f964)
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
main(int argc,char * argv[])10 main(int argc, char *argv[])
11 {
12 	int i;
13 	Waitmsg *w;
14 	long l;
15 	char *p;
16 	char err[ERRMAX];
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 	w = wait();
40 	if(w == nil){
41 		errstr(err, sizeof err);
42 		if(strcmp(err, "interrupted") == 0)
43 			goto loop;
44 		error("wait");
45 	}
46 	l = w->time[0];
47 	add("%ld.%.2ldu", l/1000, (l%1000)/10);
48 	l = w->time[1];
49 	add("%ld.%.2lds", l/1000, (l%1000)/10);
50 	l = w->time[2];
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
add(char * a,...)73 add(char *a, ...)
74 {
75 	static beenhere=0;
76 	va_list arg;
77 
78 	if(beenhere)
79 		strcat(output, " ");
80 	va_start(arg, a);
81 	vseprint(output+strlen(output), output+sizeof(output), a, arg);
82 	va_end(arg);
83 	beenhere++;
84 }
85 
86 void
error(char * s)87 error(char *s)
88 {
89 
90 	fprint(2, "time: %s: %r\n", s);
91 	exits(s);
92 }
93 
94 void
notifyf(void * a,char * s)95 notifyf(void *a, char *s)
96 {
97 	USED(a);
98 	if(strcmp(s, "interrupt") == 0)
99 		noted(NCONT);
100 	noted(NDFLT);
101 }
102