/** Compilation: gcc -o memwriter memwriter.c -lrt -lpthread **/

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>       
#include <fcntl.h>          
#include <unistd.h>
#include <semaphore.h>
#include <string.h>

#define ByteSize 512
#define MemContents "This is the way the world ends...\n"

int main() {

  int fd = shm_open("/shMemEx", O_RDWR | O_CREAT, 0644);
  if (fd < 0) { perror ("Can't open shared mem segment..."); exit (-1); }
  ftruncate(fd, ByteSize); 

  caddr_t memptr = mmap(NULL, ByteSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  if ((caddr_t)-1==memptr) { perror ("Can't get segment..."); exit (-2); }

  sem_t* semptr = sem_open("sem", O_CREAT, 0644, 0);
  if (semptr==(void*) -1) { perror ("sem_open"); exit (-2); }
  
  strcpy(memptr, MemContents); 

  /* increment the semaphore so that memreader can read */
  if (sem_post(semptr) < 0) { perror ("sem_post"); exit (-3); }

  sleep(12); /* give reader a chance */
 
  munmap(memptr, ByteSize); /* unmap the storage */
  close(fd);
  sem_close(semptr);
  shm_unlink("/shMemEx"); 
  return 0; }



