time.c 871 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include <u.h>
  2. #include <libc.h>
  3. /*
  4. * After a fork with fd's copied, both fd's are pointing to
  5. * the same Chan structure. Since the offset is kept in the Chan
  6. * structure, the seek's and read's in the two processes can
  7. * compete at moving the offset around. Hence the unusual loop
  8. * in the middle of this routine.
  9. */
  10. static long
  11. oldtime(long *tp)
  12. {
  13. char b[20];
  14. static int f = -1;
  15. int i, retries;
  16. long t;
  17. memset(b, 0, sizeof(b));
  18. for(retries = 0; retries < 100; retries++){
  19. if(f < 0)
  20. f = open("/dev/time", OREAD|OCEXEC);
  21. if(f < 0)
  22. break;
  23. if(seek(f, 0, 0) < 0 || (i = read(f, b, sizeof(b))) < 0){
  24. close(f);
  25. f = -1;
  26. } else {
  27. if(i != 0)
  28. break;
  29. }
  30. }
  31. t = atol(b);
  32. if(tp)
  33. *tp = t;
  34. return t;
  35. }
  36. long
  37. time(long *tp)
  38. {
  39. vlong t;
  40. t = nsec()/1000000000LL;
  41. if(t == 0)
  42. t = oldtime(0);
  43. if(tp != nil)
  44. *tp = t;
  45. return t;
  46. }