#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>

#define SHM_SIZE 100

#ifndef SHM_R
#define SHM_R 0200
#endif
#ifndef SHM_W
#define SHM_W 0600
#endif

#define SHM_MODE (SHM_R | SHM_W)

int main (void)
{
  int   shmida  ;
  int   shmidb  ;
  char *shmptra ;
  char *shmptrb ;
  pid_t pid    ;
  
  if ((shmida = shmget(IPC_PRIVATE, SHM_SIZE, SHM_MODE)) < 0)
    fprintf(stderr, "Error initializing shared memory A!\n");
    
  if ((shmptra = shmat(shmida, 0, 0)) == (void *)-1)
    fprintf(stderr, "Error attaching shared memory A!\n");
    
  if ((shmidb = shmget(IPC_PRIVATE, SHM_SIZE, SHM_MODE)) < 0)
    fprintf(stderr, "Error initializing shared memory B!\n");

  fprintf(stderr,"Shared memory B has ID = %d\n", shmidb);
    
  if ((pid = fork()) < 0)
  {
    fprintf(stderr, "fork() error!\n");
    exit(1);
  }
  
  if (pid == 0) sleep(2); /* make child sleep */
  
  if (pid == 0) fprintf(stdout, "Child:\n");
  else          fprintf(stdout, "Parent:\n");
  
  fprintf(stdout, "PID = %u, shmptra[0] = %c\n", pid, shmptra[0]);
  if (pid != 0) shmptra[0] = 'A' ; /* perform a write opration, see if we get a seg fault */
  
  if ((shmptrb = shmat(shmidb, 0, 0)) == (void *)-1)
    fprintf(stderr,"Error attaching shared memory B!\n");
    
  fprintf(stdout, "PID = %u, shmptrb[0] = %c\n", pid, shmptrb[0]);
  if (pid != 0) shmptrb[0] = 'B' ; /* perform a write opration, see if we get a seg fault */
  
  fprintf(stdout, "Shared memory A attached from %x to %x\n", shmptra, shmptra + SHM_SIZE);
  
  sleep(10); /* simple synchronization */
  
  if (pid != 0)
  {
    if (shmctl(shmida, IPC_RMID, 0) < 0) fprintf(stderr, "shmctl error!\n");
/*    if (shmctl(shmidb, IPC_RMID, 0) < 0) fprintf(stderr, "shmctl error!\n"); */
  }

  exit (0);
}

