Task: Shared Memory
Navigate to the labs/lab-07/tasks/shared-memory/ directory, enter the support/src/ folder, open shared_memory.c and go through the practice items below.
Use the support/tests/checker.sh script to check your solution.
./checker.sh
mmap ............................ passed ... 25
sem_wait ........................ passed ... 25
sem_post ........................ passed ... 25
match value ..................... passed ... 25
Total: 100 / 100
As you remember from the Data chapter, one way to allocate a given number of pages is to use the mmap() syscall.
Let’s look at its man page, specifically at the flags argument. Its main purpose is to determine the way in which child processes interact with the mapped pages.
Now let’s test this flag, as well as its opposite: MAP_SHARED. Compile and run the code in shared-memory/support/src/shared_memory.c.
-
See the value read by the parent is different from that written by the child. Modify the
flagsparameter ofmmap()so they are the same. -
Create a semaphore in the shared page and use it to make the parent signal the child before it can exit. Use the API defined in
semaphore.h.Be careful! The value written and read previously by the child and the parent, respectively, must not change.
One way of creating a shared semaphore is to place it within a shared memory area, as we’ve just done. This only works between “related” processes. If you want to share a semaphore or other types of memory between any two processes, you need filesystem support. For this, you should use named semaphores, created using
sem_open(). You’ll get more accustomed to such functions in the [Application Interaction chapter].