test-assert-perr.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* Test assert_perror().
  2. *
  3. * This is hairier than you'd think, involving games with
  4. * stdio and signals.
  5. *
  6. */
  7. #include <signal.h>
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <setjmp.h>
  12. #include <support/xstdio.h>
  13. jmp_buf rec;
  14. char buf[160];
  15. static void
  16. sigabrt (int unused)
  17. {
  18. longjmp (rec, 1); /* recover control */
  19. }
  20. #undef NDEBUG
  21. #include <assert.h>
  22. static void
  23. assert1 (void)
  24. {
  25. assert_perror (1);
  26. }
  27. static void
  28. assert2 (void)
  29. {
  30. assert_perror (0);
  31. }
  32. #define NDEBUG
  33. #include <assert.h>
  34. static void
  35. assert3 (void)
  36. {
  37. assert_perror (2);
  38. }
  39. int
  40. main(void)
  41. {
  42. volatile int failed = 1; /* safety in presence of longjmp() */
  43. fclose (stderr);
  44. stderr = tmpfile ();
  45. if (!stderr)
  46. abort ();
  47. signal (SIGABRT, sigabrt);
  48. if (!setjmp (rec))
  49. assert1 ();
  50. else
  51. failed = 0; /* should happen */
  52. if (!setjmp (rec))
  53. assert2 ();
  54. else
  55. failed = 1; /* should not happen */
  56. if (!setjmp (rec))
  57. assert3 ();
  58. else
  59. failed = 1; /* should not happen */
  60. rewind (stderr);
  61. xfgets (buf, 160, stderr);
  62. if (!strstr(buf, strerror (1)))
  63. failed = 1;
  64. xfgets (buf, 160, stderr);
  65. if (strstr (buf, strerror (0)))
  66. failed = 1;
  67. xfgets (buf, 160, stderr);
  68. if (strstr (buf, strerror (2)))
  69. failed = 1;
  70. return failed;
  71. }