/** * Simple program demonstrating shared memory in POSIX systems. * * Figure 3.16 * * @author Gagne, Galvin, Silberschatz * Operating System Concepts - Seventh Edition * Copyright John Wiley & Sons - 2005. * Modified by Prof. Krishna Sivalingam UMBC, Feb. 2006 */ #include #include #include #include #include #include #include int main() { /* the identifier for the shared memory segment */ int segment_id; /* a pointer to the shared memory segment */ char *shared_memory1, *shared_memory2; /* the size (in bytes) of the shared memory segment */ const int segment_size = 64; pid_t pid; /** allocate a shared memory segment */ segment_id = shmget(IPC_PRIVATE, segment_size, S_IRUSR | S_IWUSR); pid = fork(); if (pid < 0) { /* error occurred */ fprintf (stderr, "Fork Failed\n"); exit (-1); /* Get out. */ } else if (pid == 0) { /* child process */ printf ("** I am the child %d **\n", pid); /** attach the shared memory segment */ shared_memory2 = (char *) shmat(segment_id, NULL, 0); if (shared_memory2 < 0) { perror("Child: Error in Attach"); exit(-1); } printf("shared memory segment %d attached at address %p\n", segment_id, shared_memory2); /** write a message to the shared memory segment */ sprintf(shared_memory2, "Message from child"); /** now print out the string from shared memory */ printf("Child sez: *%s*\n", shared_memory2); /** now detach the shared memory segment */ if ( shmdt(shared_memory2) == -1) { fprintf(stderr, "Unable to detach\n"); } exit(0); } else { /* parent process */ printf ("I am the parent %d\n", pid); wait (NULL); printf ("Child Complete\n"); /** attach the shared memory segment */ shared_memory1 = (char *) shmat(segment_id, NULL, 0); if (shared_memory1 < 0) { perror("Child: Error in Attach"); exit(-1); } printf("shared memory segment %d attached at address %p\n", segment_id, shared_memory1); printf("Parent sez: *%s*\n", shared_memory1); /* write a message to the shared memory segment */ sprintf(shared_memory1, "Message from parent"); /** now print out the string from shared memory */ printf("Parent sez: *%s*\n", shared_memory1); /** now detach the shared memory segment */ if ( shmdt(shared_memory1) == -1) { fprintf(stderr, "Unable to detach\n"); } /** now remove the shared memory segment */ shmctl(segment_id, IPC_RMID, NULL); exit (0); } return 0; }