proc-tid0.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright (c) 2021 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/*/task never contains "0".
  17. #include <sys/types.h>
  18. #include <dirent.h>
  19. #include <signal.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <unistd.h>
  24. #include <pthread.h>
  25. static pid_t pid = -1;
  26. static void atexit_hook(void)
  27. {
  28. if (pid > 0) {
  29. kill(pid, SIGKILL);
  30. }
  31. }
  32. static void *f(void *_)
  33. {
  34. return NULL;
  35. }
  36. static void sigalrm(int _)
  37. {
  38. exit(0);
  39. }
  40. int main(void)
  41. {
  42. pid = fork();
  43. if (pid == 0) {
  44. /* child */
  45. while (1) {
  46. pthread_t pth;
  47. pthread_create(&pth, NULL, f, NULL);
  48. pthread_join(pth, NULL);
  49. }
  50. } else if (pid > 0) {
  51. /* parent */
  52. atexit(atexit_hook);
  53. char buf[64];
  54. snprintf(buf, sizeof(buf), "/proc/%u/task", pid);
  55. signal(SIGALRM, sigalrm);
  56. alarm(1);
  57. while (1) {
  58. DIR *d = opendir(buf);
  59. struct dirent *de;
  60. while ((de = readdir(d))) {
  61. if (strcmp(de->d_name, "0") == 0) {
  62. exit(1);
  63. }
  64. }
  65. closedir(d);
  66. }
  67. return 0;
  68. } else {
  69. perror("fork");
  70. return 1;
  71. }
  72. }