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 by one of the programs.

Each shared memory area needs to be uniquely identified using a long integer. Just choosing a random 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 file's inode and the 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 255 is just any integer number, but note that only the least significant 8 bits are used and the value cannot be zero.

The 0666 in the call to shmget() is an octal value that specifies the permissions for the shared memory; 0666 equates to -rw-rw-rw-.

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 &