#include #include #include #include #include #include #include #include #include #include #define BUFFER_SIZE (1024) int main (int argc, char *argv[]) { int file_fd, shm_fd; struct stat stat_buffer; char buffer[BUFFER_SIZE]; int retval; off_t left; file_fd = open ("./test-mmap.c", O_RDONLY); retval = fstat(file_fd, &stat_buffer); assert (retval != -1); shm_fd = shm_open ("my-test", O_RDWR | O_CREAT, S_IRWXU); assert (shm_fd != -1); retval = ftruncate (shm_fd, stat_buffer.st_size); assert (retval != -1); left = stat_buffer.st_size; while (left > 0) { off_t to_read; ssize_t actually_read; ssize_t actually_written; if (left > BUFFER_SIZE) { to_read = BUFFER_SIZE; } else { to_read = left; } actually_read = read (file_fd, buffer, to_read); assert (actually_read != -1); actually_written = write (shm_fd, buffer, actually_read); assert (actually_written == actually_read); left -= actually_read; } close (file_fd); printf ("done copying file to shared memory\n"); // Here, we have a shared memory segment which contains the content of our file. { void *map_one; void *map_two; char *one; char *two; map_one = mmap (0, stat_buffer.st_size, PROT_READ | PROT_EXEC | PROT_WRITE, MAP_SHARED, shm_fd, 0); assert (map_one != MAP_FAILED); map_two = mmap (0, stat_buffer.st_size, PROT_READ | PROT_EXEC | PROT_WRITE, MAP_SHARED, shm_fd, 0); assert (map_two != MAP_FAILED); one = map_one; two = map_two; printf ("one=%c\n", one[10]); printf ("two=%c\n", two[10]); one[10] = 'Y'; msync (map_one, stat_buffer.st_size, MS_SYNC); printf ("one=%c\n", one[10]); printf ("two=%c\n", two[10]); retval = munmap (map_one, stat_buffer.st_size); assert (retval != -1); retval = munmap (map_two, stat_buffer.st_size); assert (retval != -1); } return 0; }