Logo  

CS471/571 - Operating Systems

Displaying ./code/Shared_memory/shm-reader.c

#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>

#define SHM_FILE    "shm-file"
#define K   1024

struct message {
  int clr2send;
  char mbuf[K];
};

/**
 * Compile with: gcc -o reader reader.c -lrt
 */

int main(void)
{
  char mesg[K];
  struct message *m;

  int sfd = shm_open(SHM_FILE, O_RDWR, 0666);
  if (sfd < 0) {
    perror("shm_open");
    return 1;
  }

  m = mmap(NULL, sizeof(struct message), PROT_READ | PROT_WRITE, MAP_SHARED, sfd, 0);
  if (m == MAP_FAILED) {
    perror("mmap");
    close(sfd);
    shm_unlink(SHM_FILE);
    return 1;
  }

  shm_unlink(SHM_FILE);

  while (1) {
    m->clr2send++;
    while (m->clr2send > 0) usleep(100000);
    printf("%s", m->mbuf);
  }

  close(sfd);
  return 0;
}