proc-uptime.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright © 2018 Alexey Dobriyan <adobriyan@gmail.com>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #undef NDEBUG
  17. #include <assert.h>
  18. #include <errno.h>
  19. #include <string.h>
  20. #include <stdlib.h>
  21. #include <unistd.h>
  22. static unsigned long long xstrtoull(const char *p, char **end)
  23. {
  24. if (*p == '0') {
  25. *end = (char *)p + 1;
  26. return 0;
  27. } else if ('1' <= *p && *p <= '9') {
  28. unsigned long long val;
  29. errno = 0;
  30. val = strtoull(p, end, 10);
  31. assert(errno == 0);
  32. return val;
  33. } else
  34. assert(0);
  35. }
  36. static void proc_uptime(int fd, uint64_t *uptime, uint64_t *idle)
  37. {
  38. uint64_t val1, val2;
  39. char buf[64], *p;
  40. ssize_t rv;
  41. /* save "p < end" checks */
  42. memset(buf, 0, sizeof(buf));
  43. rv = pread(fd, buf, sizeof(buf), 0);
  44. assert(0 <= rv && rv <= sizeof(buf));
  45. buf[sizeof(buf) - 1] = '\0';
  46. p = buf;
  47. val1 = xstrtoull(p, &p);
  48. assert(p[0] == '.');
  49. assert('0' <= p[1] && p[1] <= '9');
  50. assert('0' <= p[2] && p[2] <= '9');
  51. assert(p[3] == ' ');
  52. val2 = (p[1] - '0') * 10 + p[2] - '0';
  53. *uptime = val1 * 100 + val2;
  54. p += 4;
  55. val1 = xstrtoull(p, &p);
  56. assert(p[0] == '.');
  57. assert('0' <= p[1] && p[1] <= '9');
  58. assert('0' <= p[2] && p[2] <= '9');
  59. assert(p[3] == '\n');
  60. val2 = (p[1] - '0') * 10 + p[2] - '0';
  61. *idle = val1 * 100 + val2;
  62. assert(p + 4 == buf + rv);
  63. }