Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

578 Interprocess Communication Chapter 15


The program opens the/dev/zerodevice and callsmmap,specifying a size of a
long integer.Note that once the region is mapped, we canclosethe device. The
process then creates a child. SinceMAP_SHAREDwas specified in the call tommap,
writes to the memory-mapped region by one process areseen by the other process. (If
we had specifiedMAP_PRIVATEinstead, this example wouldn’t work.)
The parent and the child then alternate running, incrementing a long integer in the
shared memory-mapped region, using the synchronization functions from Section 8.9.
The memory-mapped region is initialized to 0 bymmap.The parent increments it to 1,
then the child increments it to 2, then the parent increments it to 3, and so on. Note that
we have to use parentheses when we increment the value of the long integer in the
updatefunction, since we areincrementing the value and not the pointer.
The advantage of using/dev/zeroin the manner that we’ve shown is that an
actual file need not exist beforewecallmmapto create the mapped region. Mapping
/dev/zero automatically creates a mapped region of the specified size. The
disadvantage of this technique is that it works only between related processes. With
related processes, however, it isprobably simpler and moreefficient to use threads
(Chapters 11and 12). Note that no matter which technique is used, we still need to
synchronize access to the shared data.

Example — Anonymous MemoryMapping


Many implementations provide anonymous memory mapping, a facility similar to the
/dev/zerofeature. Touse this facility, we specify theMAP_ANONflag tommapand
specify the file descriptor as−1. Theresulting region is anonymous (since it’s not
associated with a pathname through a file descriptor) and creates a memory region that
can be shared with descendant processes.

The anonymous memory-mapping facility is supported by all four platforms discussed in this
text. Note, however,that Linux defines theMAP_ANONYMOUSflag for this facility,but defines
theMAP_ANONflag to be the same value for improved application portability.

To modify the program in Figure15.33 to use this facility, we make three changes:
(a) remove theopenof/dev/zero,(b) remove thecloseoffd,and (c) change the call
tommapto the following:
if ((area = mmap(0, SIZE, PROT_READ | PROT_WRITE,
MAP_ANON | MAP_SHARED, -1, 0)) == MAP_FAILED)

In this call, we specify theMAP_ANONflag and set the file descriptor to−1. Therest of
the program from Figure15.33 is unchanged.

The last two examples illustrate sharing memory among multiple related processes.
If shared memory is required between unrelated processes, thereare two alternatives.
Applications can use the XSI shared memory functions, or they can usemmapto map
the same file into their address spaces using theMAP_SHAREDflag.
Free download pdf