proc-loadavg-001.c 1.9 KB

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