shm.c

00001 /***********************************************************************
00002 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC  *
00003 * Copyright (C) 2001 by New Riders Publishing                          *
00004 * See COPYRIGHT for license information.                               *
00005 ***********************************************************************/
00006 
00007 #include <stdio.h>
00008 #include <sys/shm.h>
00009 #include <sys/stat.h>
00010 
00011 int main ()
00012 {
00013   int segment_id;
00014   char* shared_memory;
00015   struct shmid_ds shmbuffer;
00016   int segment_size;
00017   const int shared_segment_size = 0x6400;
00018 
00019   /* Allocate a shared memory segment.  */
00020   segment_id = shmget (IPC_PRIVATE, shared_segment_size,
00021                        IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
00022 
00023   /* Attach the shared memory segment.  */
00024   shared_memory = (char*) shmat (segment_id, 0, 0);
00025   printf ("shared memory attached at address %p\n", shared_memory);
00026   /* Determine the segment's size.  */
00027   shmctl (segment_id, IPC_STAT, &shmbuffer);
00028   segment_size = shmbuffer.shm_segsz;
00029   printf ("segment size: %d\n", segment_size);
00030   /* Write a string to the shared memory segment.  */
00031   sprintf (shared_memory, "Hello, world.");
00032   /* Deatch the shared memory segment.  */
00033   shmdt (shared_memory);
00034 
00035   /* Reattach the shared memory segment, at a different address.  */
00036   shared_memory = (char*) shmat (segment_id, (void*) 0x5000000, 0);
00037   printf ("shared memory reattached at address %p\n", shared_memory);
00038   /* Print out the string from shared memory.  */
00039   printf ("%s\n", shared_memory);
00040   /* Detach the shared memory segment.  */
00041   shmdt (shared_memory);
00042 
00043   /* Deallocate the shared memory segment.  */
00044   shmctl (segment_id, IPC_RMID, 0);
00045 
00046   return 0;
00047 }

Generated on Thu Sep 13 11:28:28 2007 for DCE-Eurobot by  doxygen 1.5.3