とりあえず共有メモリを使ってみる

開いて閉じるだけ。munmapは必要なのかな?

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <errno.h>

#define SHM_NAME "foo"
#define SHM_SIZE 256

int main() {
  int fd;
  char *p;

  if ((fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0666)) == -1) {
    perror("shm_open(3)");
    exit(1);
  }

  if (ftruncate(fd, SHM_SIZE) == -1) {
    perror("ftruncate(2)");
    shm_unlink(SHM_NAME);
    exit(1);
  }

  if ((p = mmap(0, SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == (void *) -1) {
    perror("mmap(2)");
    shm_unlink(SHM_NAME);
    exit(1);
  }

  sprintf(p, "Hello, Shared Memory.");
  puts(p);

  if (munmap(p, SHM_SIZE) == -1) {
    perror("munmap(2)");
    shm_unlink(SHM_NAME);
    exit(1);
  }

  if (shm_unlink(SHM_NAME) == -1) {
    perror("shm_unlink(3)");
    exit(1);
  }

  return 0;
}