proc-loadavg-001.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. /* Test that /proc/loadavg correctly reports last pid in pid namespace. */
  17. #define _GNU_SOURCE
  18. #include <errno.h>
  19. #include <sched.h>
  20. #include <sys/types.h>
  21. #include <sys/stat.h>
  22. #include <fcntl.h>
  23. #include <unistd.h>
  24. #include <sys/wait.h>
  25. int main(void)
  26. {
  27. pid_t pid;
  28. int wstatus;
  29. if (unshare(CLONE_NEWPID) == -1) {
  30. if (errno == ENOSYS || errno == EPERM)
  31. return 2;
  32. return 1;
  33. }
  34. pid = fork();
  35. if (pid == -1)
  36. return 1;
  37. if (pid == 0) {
  38. char buf[128], *p;
  39. int fd;
  40. ssize_t rv;
  41. fd = open("/proc/loadavg" , O_RDONLY);
  42. if (fd == -1)
  43. return 1;
  44. rv = read(fd, buf, sizeof(buf));
  45. if (rv < 3)
  46. return 1;
  47. p = buf + rv;
  48. /* pid 1 */
  49. if (!(p[-3] == ' ' && p[-2] == '1' && p[-1] == '\n'))
  50. return 1;
  51. pid = fork();
  52. if (pid == -1)
  53. return 1;
  54. if (pid == 0)
  55. return 0;
  56. if (waitpid(pid, NULL, 0) == -1)
  57. return 1;
  58. lseek(fd, 0, SEEK_SET);
  59. rv = read(fd, buf, sizeof(buf));
  60. if (rv < 3)
  61. return 1;
  62. p = buf + rv;
  63. /* pid 2 */
  64. if (!(p[-3] == ' ' && p[-2] == '2' && p[-1] == '\n'))
  65. return 1;
  66. return 0;
  67. }
  68. if (waitpid(pid, &wstatus, 0) == -1)
  69. return 1;
  70. if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
  71. return 0;
  72. return 1;
  73. }