#include #include #include #include #include int get_shmid( key_t shmkey, int size, int * just_created ) { int f1 = 0666 | IPC_CREAT | IPC_EXCL; int f2 = 0666; int shmid; if ( (shmid = shmget( shmkey, size, f1 )) != -1 ) { *just_created = 1; return shmid; } else if ( (shmid = shmget( shmkey, size, f2 )) != -1 ) { *just_created = 0; return shmid; } else { return -1; } } #define ID 1112232448 void * get_shmem( int size, int * just_created, int * shmid ) { key_t shmkey; char * p; errno = 0; if ( (shmkey = ftok( "/tmp", ID )) == -1 ) { printf( "ftok failed\n" ); return 0; } else if ( (*shmid = get_shmid( shmkey, 200, just_created )) == -1 ) { printf( "get_shmid failed\n" ); return 0; } else if ( (p = shmat( *shmid, NULL, 0 )) == (void *)-1 ) { printf( "shmat failed\n" ); return 0; } else { return p; } } int main() { char * p; int just_created; int shmid; char message[] = "I'm Gumby, dammit..."; if ( (p = (char *)get_shmem( 200, &just_created, &shmid )) == 0 ) { printf( "get_shmem() failed.\n" ); return 0; } else if ( just_created ) { memcpy( p, message, sizeof(message) ); printf( "Putting message into shared memory.\n" ); return 0; } else { printf( "Getting message from shared memory: %s\n", p ); shmdt( p ); shmctl( shmid, IPC_RMID, NULL ); return 0; } }