Back to index

glibc  2.9
tst-mmap-fflushsync.c
Go to the documentation of this file.
00001 /* Test program for synchronization of stdio state with file after fflush.  */
00002 
00003 #include <stdio.h>
00004 #include <error.h>
00005 #include <errno.h>
00006 
00007 static void do_prepare (void);
00008 #define PREPARE(argc, argv) do_prepare ()
00009 static int do_test (void);
00010 #define TEST_FUNCTION do_test ()
00011 #include <test-skeleton.c>
00012 
00013 static char *temp_file;
00014 static int temp_fd;
00015 
00016 static char text1[] = "Line the first\n";
00017 static char text2[] = "Line the second\n";
00018 
00019 static void
00020 do_prepare (void)
00021 {
00022   temp_fd = create_temp_file ("tst-mmap-eofsync.", &temp_file);
00023   if (temp_fd == -1)
00024     error (1, errno, "cannot create temporary file");
00025   else
00026     {
00027       ssize_t cc = write (temp_fd, text1, sizeof text1 - 1);
00028       if (cc != sizeof text1 - 1)
00029        error (1, errno, "cannot write to temporary file");
00030     }
00031 }
00032 
00033 static int
00034 do_test (void)
00035 {
00036   FILE *f;
00037   char buf[128];
00038   int result = 0;
00039   int c;
00040 
00041   f = fopen (temp_file, "rm");
00042   if (f == NULL)
00043     {
00044       perror (temp_file);
00045       return 1;
00046     }
00047 
00048   if (fgets (buf, sizeof buf, f) == NULL)
00049     {
00050       perror ("fgets");
00051       return 1;
00052     }
00053 
00054   if (strcmp (buf, text1))
00055     {
00056       printf ("read \"%s\", expected \"%s\"\n", buf, text1);
00057       result = 1;
00058     }
00059 
00060   printf ("feof = %d, ferror = %d immediately after fgets\n",
00061          feof (f), ferror (f));
00062 
00063   if (fflush (f) != 0)
00064     {
00065       printf ("fflush failed! %m\n");
00066       result = 1;
00067     }
00068 
00069   c = write (temp_fd, text2, sizeof text2 - 1);
00070   if (c == sizeof text2 - 1)
00071     printf ("wrote more to file\n");
00072   else
00073     {
00074       printf ("wrote %d != %zd (%m)\n", c, sizeof text2 - 1);
00075       result = 1;
00076     }
00077 
00078   if (fgets (buf, sizeof buf, f) == NULL)
00079     {
00080       printf ("second fgets fails: feof = %d, ferror = %d (%m)\n",
00081              feof (f), ferror (f));
00082       clearerr (f);
00083       if (fgets (buf, sizeof buf, f) == NULL)
00084        {
00085          printf ("retry fgets fails: feof = %d, ferror = %d (%m)\n",
00086                 feof (f), ferror (f));
00087          result = 1;
00088        }
00089     }
00090   if (result == 0 && strcmp (buf, text2))
00091     {
00092       printf ("second time read \"%s\", expected \"%s\"\n", buf, text2);
00093       result = 1;
00094     }
00095 
00096   fclose (f);
00097 
00098   return result;
00099 }