/*
 * Exemplo de arquivo mapeado em memória.
 * Cria uma armadilha para outro processo...
 */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

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

#define SCRATCH "armadilha"

int global = 0;
char *str = "armadilha\n";

void g();

void f() {
  g();
}

void g() {
}

int main() {
  int fd;
  char* map;
  struct stat buf;

  if ((fd = open(SCRATCH, O_RDWR, 0744)) == -1) {
    perror("open");
    return 0;
  }

  stat(SCRATCH, &buf);

  if ((map = mmap (main, buf.st_size, PROT_WRITE | PROT_READ,
		   MAP_SHARED, fd, 0)) == (void*) -1) {
    perror("mmap");
    exit(-1);
  }

  char *c = (char*) f;
  int i;
  for (i = 0; i < 100; i++)
    map[i] = c[i];

  void (*funcao)();
  funcao = map;
  f();
  funcao();
  printf("Teste\n");
  munmap(map, buf.st_size);

  close(fd);
  
  return 0;

}