File: mmap_test.c

package info (click to toggle)
dietlibc 0.34~cvs20160606-10
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 11,336 kB
  • sloc: ansic: 71,631; asm: 13,006; cpp: 1,860; makefile: 799; sh: 292; perl: 62
file content (87 lines) | stat: -rw-r--r-- 1,656 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>

#define FILENAME   "/tmp/zz_temp_mmap_test"
#define TESTSTRING "This is a test string"


int main (int argc, char * argv[])
{
   int fd;
   void *filememory_1;
   void *filememory_2;
   
   fd = open (FILENAME, O_RDWR | O_CREAT);
   
   if (fd < 0)
   {
      fprintf (stderr, "Couldn't open %s for writing\n", FILENAME);
      return (1);
   }

   unlink (FILENAME);

   write (fd, TESTSTRING, sizeof(TESTSTRING));
   lseek(fd,64*1024,SEEK_SET);
   write(fd,"fnord",5);

   /*
      Try mmapping the newly created file...
   */

   filememory_1 = mmap (NULL, 0x0100, PROT_READ, MAP_PRIVATE, fd, 0);
   
   if (filememory_1 == (void *) -1)
   {
      perror("mmap returned error");
      return (1);
   }

   /*
      Try mmapping with a bogus file descriptor... (should fail)
   */

   filememory_2 = mmap (NULL, 0x0100, PROT_READ, MAP_PRIVATE, fd+10, 0);
   
   if ((filememory_2 != (void *) -1) || (errno != 9))
   {
      fprintf (stderr, "mmap allowed a bogus file descriptor...\n");
      return (1);
   }

   /*
      Check that we can read back from the file OK
   */

   if ((*(unsigned char *) filememory_1) != TESTSTRING[0])
   {
      fprintf (stderr, "mmap doesn't give expected data...\n");
      return (1);
   }

   {
     char* c=mmap(NULL,5,PROT_READ,MAP_PRIVATE,fd,64*1024);
     if (c == MAP_FAILED) {
       perror("mmap failed");
       return 1;
     }
     if (memcmp(c,"fnord",5)) {
       fprintf(stderr,"page offset didn't work");
       return 1;
     }
   }
   
   close (fd);

   /*
      Clean up.
   */

   return (0);
}