/* * Creating a shared memory segment with POSIX API, * attaching it to the logical address space. $ g++ -Wall sharedMem1a.c++ -lrt $ ./a.out w $ ./a.out r */ #include using namespace std; #include #include #include #include #include #include #include #define SIZE 4 // sharedMem1a.c++ int main(int count, char *vect[]) { int *p, shmD ; if(count < 2) { cerr << "No 2nd argument\n"; exit(1) ; } shmD = shm_open("/myShm", O_CREAT | O_RDWR, 0777); if(shmD == -1){ cerr << "shm_open() error\n"; exit(1); } if(ftruncate(shmD, SIZE) == -1){ cerr << "ftruncate() error\n"; exit(1); } p = (int *)mmap(NULL, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shmD, 0) ; if(p == MAP_FAILED){ cerr << "mmap() error\n"; exit(1); } cout << "Attached at VA: " << p << endl; if(vect[1][0] == 'w') { cout << "Enter an integer: "; cin >> *p ; // Write data } else if(vect[1][0] == 'r') // read data cout << "The data is:" << *p << "\n"; // shm_unlink("/myShm"); return 0 ; }