1028 Chapter 49
We then use our program to map the file and copy a string into the mapped
region:
$ ./t_mmap s.txt hello
Current string=
Copied "hello" to shared memory
The program displayed nothing for the current string because the initial value of
the mapped files began with a null byte (i.e., zero-length string).
Next, we use our program to again map the file and copy a new string into the
mapped region:
$ ./t_mmap s.txt goodbye
Current string=hello
Copied "goodbye" to shared memory
Finally, we dump the contents of the file, 8 characters per line, to verify its contents:
$ od -c -w8 s.txt
0000000 g o o d b y e nul
0000010 nul nul nul nul nul nul nul nul
*
0002000
Our trivial program doesn’t use any mechanism to synchronize access by multiple
processes to the mapped file. However, real-world applications typically need to
synchronize access to shared mappings. This can be done using a variety of tech-
niques, including semaphores (Chapters 47 and 53) and file locking (Chapter 55).
We explain the msync() system call used in Listing 49-2 in Section 49.5.
Listing 49-2: Using mmap() to create a shared file mapping
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– mmap/t_mmap.c
#include <sys/mman.h>
#include <fcntl.h>
#include "tlpi_hdr.h"
#define MEM_SIZE 10
int
main(int argc, char *argv[])
{
char *addr;
int fd;
if (argc < 2 || strcmp(argv[1], "--help") == 0)
usageErr("%s file [new-value]\n", argv[0]);
fd = open(argv[1], O_RDWR);
if (fd == -1)
errExit("open");