/** Compilation: gcc -o memreader memreader.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, 0644); 
  if (fd < 0) { perror ("Can't get file descriptor..."); exit (-1); }
  
  caddr_t memptr = mmap(NULL, ByteSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  if ((caddr_t)-1==memptr) { perror ("Can't access segment..."); exit (-1); }
  
  sem_t* semptr = sem_open("sem", O_CREAT, 0644, 0);
  if (semptr == (void*)-1) { perror ("sem open"); exit (-1); }

  if (!sem_wait(semptr)) { /* wait until semaphore != 0 */
    int i;
    for (i = 0; i < strlen(MemContents); i++)
         write(STDOUT_FILENO, memptr + i, 1); 
    sem_post(semptr); }

  munmap(memptr, ByteSize);
  close(fd);
  sem_close(semptr);
  unlink("/shMemEx");
  return 0; }
  
  
  
