xref: /plan9/sys/src/libc/9sys/times.c (revision 7dd7cddf99dd7472612f1413b4da293630e6b1bc)
1 #include <u.h>
2 #include <libc.h>
3 
4 static
5 char*
skip(char * p)6 skip(char *p)
7 {
8 
9 	while(*p == ' ')
10 		p++;
11 	while(*p != ' ' && *p != 0)
12 		p++;
13 	return p;
14 }
15 
16 /*
17  *  after a fork with fd's copied, both fd's are pointing to
18  *  the same Chan structure.  Since the offset is kept in the Chan
19  *  structure, the seek's and read's in the two processes can be
20  *  are competing moving the offset around.  Hence the unusual loop
21  *  in the middle of this routine.
22  */
23 long
times(long * t)24 times(long *t)
25 {
26 	char b[200], *p;
27 	static int f = -1;
28 	int i, retries;
29 	ulong r;
30 
31 	memset(b, 0, sizeof(b));
32 	for(retries = 0; retries < 100; retries++){
33 		if(f < 0)
34 			f = open("/dev/cputime", OREAD|OCEXEC);
35 		if(f < 0)
36 			break;
37 		if(seek(f, 0, 0) < 0 || (i = read(f, b, sizeof(b))) < 0){
38 			close(f);
39 			f = -1;
40 		} else {
41 			if(i != 0)
42 				break;
43 		}
44 	}
45 	p = b;
46 	if(t)
47 		t[0] = atol(p);
48 	p = skip(p);
49 	if(t)
50 		t[1] = atol(p);
51 	p = skip(p);
52 	r = atol(p);
53 	if(t){
54 		p = skip(p);
55 		t[2] = atol(p);
56 		p = skip(p);
57 		t[3] = atol(p);
58 	}
59 	return r;
60 }
61