#include #include #include #define SHMKEY 1000 typedef struct _DATA { int value; char sText[ 50 ]; } DATA, *PDATA; int g_shmid; int main( void ) { int i; PDATA pdata; /* create the shared memory segment and get its id */ g_shmid = shmget( SHMKEY, sizeof( DATA ), 0644 | IPC_CREAT ); /* bail out if it failed */ if ( -1 == g_shmid ) { perror( "shared memory create" ); exit( EXIT_FAILURE ); } /* get a pointer to the shared memory */ pdata = (PDATA) shmat( g_shmid, 0, 0 ); /* create a child process */ if ( 0 == fork() ) { if ( -1 == (int) pdata ) perror( "child memory attach" ); else { /* put some data in the structure */ srand( time( NULL ) ); pdata->value = rand(); strcpy( pdata->sText, "Hi, dad!" ); printf( "Child: value=%d text='Hi, dad!'\n", pdata->value ); /* detach the memory from this process */ shmdt( (char*) pdata ); } } else { /* let child go first */ wait( 0 ); if ( -1 == (int) pdata ) perror( "parent memory attach" ); else { /* print out whatever is in the structure */ printf( "Parent: value=%d text='%s'\n", pdata->value, pdata->sText ); /* detach the memory from this process */ shmdt( (char*) pdata ); /* destroy the segment--note that this is only * done in the parent and after the child has finished */ if ( -1 == shmctl( g_shmid, IPC_RMID, NULL ) ) perror( "shared memory delete" ); } } }