tst-mmap-fflushsync.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /* Test program for synchronization of stdio state with file after fflush. */
  2. #include <stdio.h>
  3. #include <error.h>
  4. #include <errno.h>
  5. static void do_prepare (void);
  6. #define PREPARE(argc, argv) do_prepare ()
  7. static int do_test (void);
  8. #define TEST_FUNCTION do_test ()
  9. #include <test-skeleton.c>
  10. static char *temp_file;
  11. static int temp_fd;
  12. static char text1[] = "Line the first\n";
  13. static char text2[] = "Line the second\n";
  14. static void
  15. do_prepare (void)
  16. {
  17. temp_fd = create_temp_file ("tst-mmap-eofsync.", &temp_file);
  18. if (temp_fd == -1)
  19. error (1, errno, "cannot create temporary file");
  20. else
  21. {
  22. ssize_t cc = write (temp_fd, text1, sizeof text1 - 1);
  23. if (cc != sizeof text1 - 1)
  24. error (1, errno, "cannot write to temporary file");
  25. }
  26. }
  27. static int
  28. do_test (void)
  29. {
  30. FILE *f;
  31. char buf[128];
  32. int result = 0;
  33. int c;
  34. f = fopen (temp_file, "rm");
  35. if (f == NULL)
  36. {
  37. perror (temp_file);
  38. return 1;
  39. }
  40. if (fgets (buf, sizeof buf, f) == NULL)
  41. {
  42. perror ("fgets");
  43. return 1;
  44. }
  45. if (strcmp (buf, text1))
  46. {
  47. printf ("read \"%s\", expected \"%s\"\n", buf, text1);
  48. result = 1;
  49. }
  50. printf ("feof = %d, ferror = %d immediately after fgets\n",
  51. feof (f), ferror (f));
  52. if (fflush (f) != 0)
  53. {
  54. printf ("fflush failed! %m\n");
  55. result = 1;
  56. }
  57. c = write (temp_fd, text2, sizeof text2 - 1);
  58. if (c == sizeof text2 - 1)
  59. printf ("wrote more to file\n");
  60. else
  61. {
  62. printf ("wrote %d != %zd (%m)\n", c, sizeof text2 - 1);
  63. result = 1;
  64. }
  65. if (fgets (buf, sizeof buf, f) == NULL)
  66. {
  67. printf ("second fgets fails: feof = %d, ferror = %d (%m)\n",
  68. feof (f), ferror (f));
  69. clearerr (f);
  70. if (fgets (buf, sizeof buf, f) == NULL)
  71. {
  72. printf ("retry fgets fails: feof = %d, ferror = %d (%m)\n",
  73. feof (f), ferror (f));
  74. result = 1;
  75. }
  76. }
  77. if (result == 0 && strcmp (buf, text2))
  78. {
  79. printf ("second time read \"%s\", expected \"%s\"\n", buf, text2);
  80. result = 1;
  81. }
  82. fclose (f);
  83. return result;
  84. }