Shared Memory Example

Here's one for the noobs (from a noob). This demonstrates the use of shared memory. It's a program that spawns 10 children, and each one gets a special "babytalk" word to say. Each waits a random amount of time, and then writes it word into shared memory. Each child loops forever.

The parent loops forever, and every two seconds, prints whatever is in shared memory. The last child to write to memory "wins" and is "heard" by the parent.

Shared memory is a file that's treated like memory (or memory that happens to be written to a file). The filename is the name of the memory. You use mmap() like you would use malloc().

This is useful because you can duplicate a data structure across processes. (I'm thinking of using it for a kind of "scoreboard" where child processes write their results into shared memory.)

Here's the code:

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

struct d {
  char word[20];
char babytalk[10][6] = {
  "baa", "boo", "waaah", "urp", "eep", "naah", "yeee", "coo", "guh", "ooh"

void child_babble(struct d *shared, char *word)
    sleep( rand() & 0x5 ); 

void main() {
  struct d *shared;
  int fd;

  // create and size shared memory
  fd = open("/tmp/sharedmem", O_CREAT|O_TRUNC|O_RDWR, 0666);
  printf("fd: %d\n", fd);
  lseek(fd,sizeof(struct d)-1,SEEK_SET);

  // turn the file into shared memory
  shared = mmap( NULL, sizeof(struct d), PROT_READ|PROT_WRITE, 
                 MAP_SHARED, fd, 0);
  if (shared==MAP_FAILED) 
    printf("ERROR: %d\n", errno);
  printf("shared: %d\n", (unsigned int) shared);

  // spawn 10 children
  int i;
    if (fork()==0) 
      child_babble( shared, babytalk[i] );

    printf("%s\n", shared->word );
    sleep( 2 );
mem.c1.15 KB