#include #include #include #include #include #include #include struct data_struct { float f1; int f2; int size; }; int main(int argc, char * argv[]) { int n = 0; //shared memory stuff //create a segment with shmget int segment_id; //segment_id =shmget(IPC_PRIVATE, sizeof(data_struct), 0777 | IPC_CREAT | IPC_EXCL); //using ftok int key = ftok("shm.cpp",'A'); if(key == -1) { perror("ftok"); exit(1); } segment_id=shmget(key, sizeof(data_struct), 0777 | IPC_CREAT |IPC_EXCL); if(segment_id == -1) { perror("shmget"); exit(1); } data_struct * s = (data_struct *)shmat(segment_id, NULL, 0); // attach if(s == (data_struct *)-1) { perror("shmat"); exit(1); } printf("s->size is %d\n", s->size); s->size = n; printf("s->size is now %d\n", s->size); int res = shmdt(s); //detach the segment if(res == -1) { perror("shmdt"); } printf("value of the pointer is %d\n",s); //printf("value of s->size is %d\n",s->size); // this would core dump s = (data_struct *)shmat(segment_id,NULL,0); //attach if(s == (data_struct *)-1) { perror("shmat"); } printf("we've reattached, s->size is now %d\n",s->size); printf("-------------------------------------\n"); res = shmdt(s); //detact the segment pointed to by s if(res == -1) { perror("shmdt"); } res = shmctl(segment_id, IPC_RMID, NULL); // destroy a segment if(res == -1) { perror("shmctl(RMID)"); } exit(0); }