POSIX Shared Memory
- 3.5 plus Kerrisk chapter 54
- Kerrisk also covers
- System V Shared Memory chapter 48
- Memory Mappings chapter 49
- We some how need to ask the kernel to allow us to share memory
- We then should be able to read/write to this memory.
- Plus we need a way to
- Lock this memory for a unique write.
- Race Condition:
- When two or more processes need access to a shared object
- And it is unpredictable as to which one will gain access to that object.
- A condition where the behavior of a system is dependent on the sequence of uncontrollable events, which results in unexpected or inconsistent results.
- We will do some simple shared memory computations for now, but we will need something to help us eliminate race conditions later.
- I will do a pi computation with n processes
- The leader will fork n-1 times
- workers will compute pi and store it in shared memory
- The workers will exit, giving the leader an indication that work is done
- At this point, it will compute the final sum.
- Take a look at piStart.cpp.
- This avoids race conditions, as they can not occur.
- After making the notes, this is too complex to do in class, so we will look at the code in smemPi.cpp
- Adding shared memory
- We need sys/mman.h, sys/stat.h and fcntl
- >
int shm_open(const char *name, int oflag, mode_t mode);
-
name is a c style string, the shared memory
-
oflag is the open flag
- In this case we open it for read/write
- And we open it creating a new file if one does not exist
- There are other flags, but this will do.
-
mode gives the file permissions
- In this case we do the equivalent of chmod u=rw, go-rwx
- This returns a file descriptor
- A small integer representing a file.
- -1 means error
-
int shm_unlink(const char *name);
- If you fail to call this, the "file" will not be removed
- look at /dev/shm
- Shared memory objects are not closed when a fork occurs (unless specified to do so).
- Shared memory objects can be opened by other processes as well.
- we need to make the file the right size with
ftruncate
- At this point, we could read, write, lseek , but that is
- Three more commands not one
- Not in the spirit of the thing.
- so
mmap
- Next we will map the shared memory to a pointer with
mmap
- The man page says we can close the fd now, so I will.