Writing Shared Memory Segments

<< prev next >>

This example shows how to write to shared memory using the Shared Memory Arena library.

We already ran this program in the last example in Reading Shared Memory Segments.

Looking at the Source

From the source file examples/tutorial/write.c

First we include some header files:

#include <unistd.h> /* for usleep() */
#include <shm_arena.h> /* for Shared Memory Arena Library */

We have a main function:

int main(void)
{
int *ptr;
int running = 1;

We get some a shared memory just like in the read example:

ptr = (int *) sm_get(sizeof(int), "count");
if(!ptr)
{
printf("sm_get() failed\n");
return 1;
}

We initialize the shared memory while holding a segment write lock:

sm_wrlock(ptr);
*ptr = 0;
sm_unlock(ptr);

We then loop: write-locking, writing, unlocking, and sleeping until the count in shared memory is greater than 10:

while(running)
{
sm_wrlock(ptr);
if(++*ptr > 10)
running = 0;
sm_unlock(ptr);
sleep(1);
}
return 0;
}

<< prev next >>


Shared Memory Arena version RC-0.0.25