/* * shmread.c * Reads a message from a shared memory segment. */ #include #include #include #include #include #include #include #define MAX_SIZE 512 int main(int argc, char **argv) { key_t key; int shm; void *ptr; char buffer[512]; if((key=ftok("sharedmem",'a'))==-1) { fprintf(stdout,"failed to get key for shared memory segment %d, %s\n",errno,strerror(errno)); fflush(stdout); return -1; } if((shm=shmget(key,MAX_SIZE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP))==-1) { fprintf(stdout,"failed to allocate shared memory segment %d, %s\n",errno,strerror(errno)); fflush(stdout); return -1; } fprintf(stdout,"shared memory segment %x allocated\n",key); fflush(stdout); if(((int)(ptr=shmat(shm,NULL,0)))==-1) { fprintf(stdout,"failed to attach shared memory segment to pointer %d, %s\n",errno,strerror(errno)); fflush(stdout); return -1; } strcpy(buffer,ptr); fprintf(stdout,"memory contents: %s\n",buffer); if(shmdt(ptr)==-1) { fprintf(stdout,"failed to dettached pointer from shared memory segment %d, %s\n",errno,strerror(errno)); fflush(stdout); return -1; } return 0; }