# include <iostream.h>
# include <sys/types.h>
# include <sys/ipc.h>
# include <sys/shm.h>
# include <unistd.h>
# define SHM_SIZE 100
# define SHM_MODE SHM_R/SHM_W

struct shareMemory
{
    int countA;
};

int main ()
{
    int pid;          // process id
    int shmid;     // share memory id
    int countB;
    struct shareMemory* memoryPtr;     // pointer pointed to shared
//memory segment
    cout << "process" << '\t'
            << "count (before)" << '\t'
            << "count (after)" <<endl;

    // create a shared memory segment, and see if it is successful
    if ((shmid=shmget (IPC_PRIVATE, SHM_SIZE, SHM_MODE)) <0)
    {
         cout << "Shared memory segment cannot be created."<< endl;
         return 1;     // terminate with error
    }

    // get a pointer to the shared memory segment, and see if it is
//successful

/*
    else if ((memoryPtr=shmget (shmid, 0, 0)) == (struct
shareMemory*)-1)
    {
cout << "The pointer cannot point to the shared memory segment."
<<endl;
return 1;
    }
*/
    // create a child process by fork, and see if it is successful
    else if ( ( pid=fork () ) < 0 )
    {
         cout << "The new process cannot be created." << endl;
         return 1;
    }

    else
    for (int I=0; I<5; I++)
    {
         if (pid !=0) // pid non zero from parent process
         {
countB = memoryPtr->countA;
countB = countB + 2;
memoryPtr->countA = countB;

cout << "parent" << '\t' << '\t'
       << countB << '\t' << '\t'
        <<memoryPtr-> countA  <<endl;
         }

         else     // pid zero from child process
         {
              countB=memoryPtr-> countA;
              countB++;
              memoryPtr->countA = countB;

              cout << "child" << '\t' << '\t'
                      << countB << '\t' <<'\t'
                      << memoryPtr->countA << endl;
         }
    }
return 0; // termininate with no error
}

