Source code for shmem.c


    1: #include <stdio.h>
    2: #include <stdlib.h>
    3: #include <sys/shm.h>
    4: 
    5: #define SHMKEY           1000
    6: 
    7: typedef struct _DATA  {
    8:     int  value;
    9:     char sText[ 50 ];
   10: } DATA, *PDATA;
   11: 
   12: int g_shmid;
   13: 
   14: int main( void )
   15: {
   16:     int   i;
   17:     PDATA pdata;
   18: 
   19:     /* create the shared memory segment and get its id */
   20:     g_shmid = shmget( SHMKEY, sizeof( DATA ), 0644 | IPC_CREAT );
   21: 
   22:     /* bail out if it failed */
   23:     if ( -1 == g_shmid )  {
   24:         perror( "shared memory create" );
   25:         exit( EXIT_FAILURE );
   26:     }
   27: 
   28:     /* get a pointer to the shared memory */
   29:     pdata = (PDATA) shmat( g_shmid, 0, 0 );
   30: 
   31:     /* create a child process */
   32:     if ( 0 == fork() )  {
   33:         if ( -1 == (int) pdata )
   34:             perror( "child memory attach" );
   35:         else  {
   36:             /* put some data in the structure */
   37:             srand( time( NULL ) );
   38:             pdata->value = rand();
   39:             strcpy( pdata->sText, "Hi, dad!" );
   40:             printf( "Child:  value=%d  text='Hi, dad!'\n", pdata->value );
   41: 
   42:             /* detach the memory from this process */
   43:             shmdt( (char*) pdata );
   44:         }
   45:     }
   46:     else  {
   47:         /* let child go first */
   48:         wait( 0 );
   49: 
   50:         if ( -1 == (int) pdata )
   51:             perror( "parent memory attach" );
   52:         else  {
   53:             /* print out whatever is in the structure */
   54:             printf( "Parent: value=%d  text='%s'\n", pdata->value, 
   55:                     pdata->sText );
   56: 
   57:             /* detach the memory from this process */
   58:             shmdt( (char*) pdata );
   59: 
   60:             /* destroy the segment--note that this is only
   61:              * done in the parent and after the child has finished 
   62:              */
   63:             if ( -1 == shmctl( g_shmid, IPC_RMID, NULL ) )
   64:                 perror( "shared memory delete" );
   65:         }
   66:     }
   67: }
   68: 
   69: