/*
 * Exemplo de uso de memória compartilhada.
 * Pai e filho irão se sincronizar por meio de semáforos.
 */ 
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <semaphore.h>

#define SHMSZ 2*sizeof(sem_t)

int main() {
  int shmid;
  key_t key;
  char *shm;
  sem_t* p_sem;
  
  /* Chave arbitrária para o segmento compartilhado */
  key = 5677;

  /* Criação do segmento de memória e obtenção do seu identificador. */
  if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {
    perror("shmget");
    exit(1);
  }

  /* Segmento é associado ao espaço de endereçamento */
  if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
    perror("shmat");
    exit(1);
  }

  p_sem = (sem_t*) shm;
  sem_init(&p_sem[0], 1, 0);
  sem_init(&p_sem[1], 1, 0);  
  
  if (fork() != 0) {
    sem_post(&p_sem[0]);    
    sem_wait(&p_sem[1]);
    printf("Pai recebeu sinal do filho.\n");
    sem_destroy(&p_sem[1]);    
  }
  else {
    sem_post(&p_sem[1]); 
    sem_wait(&p_sem[0]);
    printf("Filho recebeu sinal do pai.\n");
    sem_destroy(&p_sem[0]);      
  }    

  shmctl(shmid, IPC_RMID, NULL);      
  shmdt(shm);
    
  return 0;
}