/* Race in shared memory $ g++ -Wall sharedMem4.c++ $ ./a.out 5000000 */ #include using namespace std; #include #include #include #include #include #include #define SIZE 4 int main(int count, char *vect[]) { int shmID, *p, cPID, n, status ; struct shmid_ds buff; if(count < 2) { cerr << "No 2nd argument\n"; exit(1) ; } shmID = shmget(ftok("/home/goutam", 1234), SIZE, IPC_CREAT | 0777); if(shmID == -1) { cerr << "Error in shmget" ; exit(1) ; } p = (int *) shmat(shmID, 0, 0777); p[0] = 0; // shared memory initialized to 0 n = atoi(vect[1]); cPID = fork(); if(cPID == -1){ cerr << "fork() error\n"; shmdt(p); shmctl(shmID, IPC_RMID, &buff); exit(1); } if(cPID > 0){ // parent int i; for(i=1; i<=n; ++i) p[0]=p[0]+1; waitpid(cPID, &status, 0); cout << "p[0]: " << p[0] << "\n"; shmdt(p); shmctl(shmID, IPC_RMID, &buff); } else { // child int i; for(i=1; i<=n; ++i) p[0]=p[0]-1; } return 0 ; }