Shared memory
A segment common to several processes with shm_open, ftruncate, mmap with MAP_SHARED, munmap and shm_unlink, the lack of synchronisation and the semaphore, then choosing between pipe, signal and shared memory.
- 24 cards
- 4 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
A few cards from the deck
Shared memory: what is it?
Show the answer
An area that several processes map into their address space: what one writes there, the others see, with no copy made by the kernel.
It is the fastest means of communication between processes on one machine. But the system sets no rule there: the programs must coordinate themselves.
What are a and *p printed by the parent, both starting from 0?
```c
int a = 0;
int *p = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
*p = 0;
if (fork() == 0) { a = 7; *p = 7; _exit(0); }
wait(NULL);
printf("%d %d\n", a, *p);`0 77 70 07 0
Show the answer
0 7After
fork,aexists as two independent copies: the child changes its own.*prefers to the same physical page in both processes. Program run:0 7.A new segment created by shm_open has … size: call … before mapping it with mmap.
Show the answer
A new segment created by shm_open has zero size: call ftruncate before mapping it with mmap.
Touching a page beyond the end of the segment raises
SIGBUS.ftruncate(fd, size)reserves the room.shm_open: what is it?
Show the answer
The call that creates or opens a segment designated by a name of the form /name, and returns a file descriptor.
Two processes that open the same name get the same segment. A brand-new segment has size zero:
ftruncateis needed before mapping it for use.Two processes share a buffer in shared memory: one writes a structure with several fields, the other reads it. The reader sometimes gets half-updated structures. What should be done?
- Protect the accesses with a shared semaphore
- Map with MAP_PRIVATE so each has its up-to-date copy
- Call ftruncate again so the segment is big enough
- Call shm_unlink before each read to empty the segment
Show the answer
Protect the accesses with a shared semaphore
The reader comes by while the writer has not finished: nothing in shared memory forces waiting. The semaphore makes writing and reading sections that do not overlap.
MAP_PRIVATEwould cut the communication.