Project

General

Profile

Bug #5379 ยป mmap_write.c

demo - Andriy Gapon, 2015-11-11 01:53 PM

 
1
#include <sys/types.h>
2
#include <sys/mman.h>
3
#include <sys/stat.h>
4

    
5
#include <fcntl.h>
6
#include <stdio.h>
7
#include <stdlib.h>
8
#include <unistd.h>
9

    
10
static const int SIZE = 4096;
11

    
12
int main (int argc, char *argv[])
13
{
14
        struct stat sb;
15
        off_t i;
16
        char *p;
17
        int fd;
18

    
19
        if (argc < 2) {
20
                fprintf (stderr, "usage: %s <file>\n", argv[0]);
21
                return 1;
22
        }
23

    
24
        fd = open(argv[1], O_CREAT | O_EXCL | O_RDWR, 0660);
25
        if (fd == -1) {
26
                perror ("open");
27
                return 1;
28
        }
29
	unlink(argv[1]);
30

    
31
        if (ftruncate(fd, SIZE) == -1) {
32
                perror ("ftruncate");
33
                return 1;
34
        }
35

    
36
        p = mmap(NULL, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
37
        if (p == MAP_FAILED) {
38
                perror ("mmap");
39
                return 1;
40
        }
41

    
42
	printf("press enter to update the file, 'q' to exit\n");
43
	i = 0;
44
	while(getchar() != 'q') {
45
                p[i] = (char)i;
46
		i = (i + 1) % SIZE;
47
		if (msync(p, SIZE, MS_SYNC) == -1) {
48
			perror ("msync");
49
			return 1;
50
		}
51

    
52
		if (fstat(fd, &sb) == -1) {
53
			perror ("fstat");
54
			return 1;
55
		}
56
		printf("mtime = %lu\n", sb.st_mtime);
57
	}
58

    
59
        if (munmap(p, SIZE) == -1) {
60
                perror ("munmap");
61
                return 1;
62
        }
63

    
64
        if (close(fd) == -1) {
65
                perror ("close");
66
                return 1;
67
        }
68

    
69
        return (0);
70
}
71

    
    (1-1/1)