#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <assert.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <semaphore.h>

typedef struct
{
  sem_t message_ready;
  sem_t buffer_ready;
  size_t size;
  char contents[];
} SharedMemory;



int main()
{
  int fd = shm_open("/my_example_shared_memory",O_CREAT | O_RDWR,0644);
  assert(fd != -1);
  ftruncate(fd,sizeof(SharedMemory)+1);
  SharedMemory* shm = mmap(0,15ull*1024ull*1024ull*1024ull,PROT_READ | PROT_WRITE, MAP_SHARED,fd,0);
  sem_init(&(shm->message_ready),1,0);
  sem_init(&(shm->buffer_ready),1,1);
  while (1) {
    printf("> ");
    char* line = 0;
    size_t size = 0;
    getline(&line,&size,stdin);
    line[strlen(line)-1] = 0;
    //printf("writing '%s'\n",line);
    ftruncate(fd,sizeof(SharedMemory)+strlen(line)+1);
    printf("will wait\n");
    sleep(5);
    sem_wait(&(shm->buffer_ready));
    strcpy(shm->contents,line);
    strcat(shm->contents,"\n");
    sem_post(&(shm->message_ready));
  }
  return -1;
}