SHARED MEMORY

There can be many situations where you need to share data between processes in a fast and efficient way. One method to do this is for one program to create an area of shared memory and write to it and then for another program to access that shared memory and make use of the data. You can use the shmget() and shmat() functions that create and then attach shared memory respectively. The example below shows two programs; one creates the shared memory and writes to it and the other reads from it, though both can interact freely with the shared data if you wish. If you're concerned about both programs writing to the shared memory at the same time, you can include in the shared data a flag to indicate when it is in use.

Each shared memory area needs to be uniquely identified using a long integer. Just choosing a value is poor practice since it provides no guarantee that clashes do not occur with other programs. One way to create a unique identifier is to use the ftok() function. This takes two arguments: a filepath and a integer reference. ftok() uses the combination of the inode and reference to create a reasonably unique key. In the example, the filepath is the current directory so providing both programs run from the same directory they can communicate. The 999 is just any number, which could be a project number, the next number from a register of shared memory areas, etc.

Source Code

Program 1

Program 2

These programs need no special libraries and can be compiled using

gcc rp-shared-memory-p1.c -o rp-shared-memory-p1

gcc rp-shared-memory-p2.c -o rp-shared-memory-p2

You then need to run the two programs in separate sessions, or use the & control operator to run one in background, e.g.

./rp-shared-memory-p1 &

./rp-shared-memory-p2