1 | #include <sys/mman.h>
|
---|
2 | #include <sys/stat.h>
|
---|
3 | #include <sys/types.h>
|
---|
4 |
|
---|
5 | #include <errno.h>
|
---|
6 | #include <fcntl.h>
|
---|
7 | #include <stdio.h>
|
---|
8 | #include <string.h>
|
---|
9 |
|
---|
10 |
|
---|
11 | static const int skDataLen = 4096;
|
---|
12 | static const int skTruncatedLen = 3766;
|
---|
13 | // just anything smaller than skDataLen, to leave a gap in the last page
|
---|
14 | static char testData[skDataLen];
|
---|
15 |
|
---|
16 |
|
---|
17 | int
|
---|
18 | main()
|
---|
19 | {
|
---|
20 | int fileDes = open("mmap_zero_test.data", O_CREAT | O_RDWR | O_TRUNC);
|
---|
21 | if (fileDes == -1) {
|
---|
22 | fprintf(stderr, "unable to create test-file - errno=%x\n", errno);
|
---|
23 | return 1;
|
---|
24 | }
|
---|
25 |
|
---|
26 | memset(testData, 'x', skDataLen);
|
---|
27 |
|
---|
28 | ssize_t bytesWritten = write(fileDes, testData, skDataLen);
|
---|
29 | if (bytesWritten < 0) {
|
---|
30 | fprintf(stderr, "unable to write data - errno=%x\n", errno);
|
---|
31 | return 1;
|
---|
32 | }
|
---|
33 | if (bytesWritten != skDataLen) {
|
---|
34 | fprintf(stderr, "wrote only %d bytes instead of %d\n", bytesWritten,
|
---|
35 | skDataLen);
|
---|
36 | return 1;
|
---|
37 | }
|
---|
38 |
|
---|
39 | int res = ftruncate(fileDes, skTruncatedLen);
|
---|
40 | if (res == -1) {
|
---|
41 | fprintf(stderr, "unable to set size of file - errno=%x\n", errno);
|
---|
42 | return 1;
|
---|
43 | }
|
---|
44 |
|
---|
45 | void* pa
|
---|
46 | = mmap(NULL, skTruncatedLen + 1, PROT_READ, MAP_PRIVATE, fileDes, 0);
|
---|
47 | if (pa == NULL) {
|
---|
48 | fprintf(stderr, "unable to mmap the file - errno=%x\n", errno);
|
---|
49 | return 1;
|
---|
50 | }
|
---|
51 |
|
---|
52 | int mappedStrLen = strlen((char*)pa);
|
---|
53 | if (mappedStrLen != skTruncatedLen) {
|
---|
54 | fprintf(stderr, "mapped string length is %d bytes instead of %d\n",
|
---|
55 | mappedStrLen, skTruncatedLen);
|
---|
56 | return 1;
|
---|
57 | }
|
---|
58 |
|
---|
59 | return 0;
|
---|
60 | }
|
---|