adjtime.c 1007 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include <limits.h>
  2. #include <sys/time.h>
  3. #include <sys/timex.h>
  4. #include <errno.h>
  5. #define MAX_SEC (LONG_MAX / 1000000L - 2)
  6. #define MIN_SEC (LONG_MIN / 1000000L + 2)
  7. #ifndef MOD_OFFSET
  8. #define modes mode
  9. #endif
  10. int
  11. adjtime(const struct timeval * itv, struct timeval * otv)
  12. {
  13. struct timex tntx;
  14. if (itv)
  15. {
  16. struct timeval tmp;
  17. /* We will do some check here. */
  18. tmp.tv_sec = itv->tv_sec + itv->tv_usec / 1000000L;
  19. tmp.tv_usec = itv->tv_usec % 1000000L;
  20. if (tmp.tv_sec > MAX_SEC || tmp.tv_sec < MIN_SEC)
  21. {
  22. errno = EINVAL;
  23. return -1;
  24. }
  25. tntx.offset = tmp.tv_usec + tmp.tv_sec * 1000000L;
  26. tntx.modes = ADJ_OFFSET_SINGLESHOT;
  27. }
  28. else
  29. {
  30. tntx.modes = 0;
  31. }
  32. if (adjtimex(&tntx) < 0) return -1;
  33. if (otv) {
  34. if (tntx.offset < 0)
  35. {
  36. otv->tv_usec = -(-tntx.offset % 1000000);
  37. otv->tv_sec = -(-tntx.offset / 1000000);
  38. }
  39. else
  40. {
  41. otv->tv_usec = tntx.offset % 1000000;
  42. otv->tv_sec = tntx.offset / 1000000;
  43. }
  44. }
  45. return 0;
  46. }