#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#define SHMSZ 4
using namespace std;

int main(void) {
     int shmid;
     key_t key;
     int *shm;
     key=1010;
     //request from system shared memory
     shmid=shmget(key,SHMSZ,IPC_CREAT|0666);
     cout<<"SHMID="<< shmid<<endl;

     pid_t pid;
     int status;
     pid=fork();

     //attach that memory as part of both processes address space
     //the id of address space,NULL=a char pointer to address space,access flags
     // if SHM_RDONLY readonly. if 0 READDWRITE
     shm=(int*)shmat(shmid,NULL,0);
     if (shm<0) {
        cout<< "error getting a shared memory chunk " << endl;
        exit(-1);
     }
     if (pid==0) {
       cout<< "Child="<<pid<< "My var"<< *shm<< endl;
       for (int i=0;i<10;i++) {
           *shm+=1;
           cout<< "child="<< pid<<"my var="<<*shm<< endl;
        }
        exit(120);
     } else {
          cout<< "Parent=" <<getpid() <<"child="<< pid<<"My var=" <<*shm<< endl;
          for( int i=0;i<10; i++) {
              *shm-=1;
              cout<< "Parent My_Var=" << *shm << endl;
          }
          pid_t test=wait(&status);
          cout<< "child ID=" <<test<< "status=" << WEXITSTATUS(status)<< endl;
     }
     cout<< "Final =" <<*shm<< endl;
     return 0;
}
