/* sharedmem.c Started by Jeff Ondich on 4/11/96 Last modified on 4/3/02 This program demonstrates how to use shared memory in Linux. */ #include #include #include #include #include #include #include #include #define kSharedMemKey ((key_t)1113) #define kSharedBufferSize 100 int main( void ) { int pid, status; char *pSharedBuffer; int sharedBufferID; /* Create the shared memory. */ sharedBufferID = shmget( kSharedMemKey, kSharedBufferSize, 0664 | IPC_CREAT | IPC_EXCL ); if( sharedBufferID == -1 ) { perror( "Shmget trouble" ); exit( 1 ); } /* Attach the shared memory to the current process' address space. */ pSharedBuffer = (char *)shmat( sharedBufferID, (char *)0, 0 ); if( pSharedBuffer == (char *)-1 ) { perror( "Shmat trouble" ); shmctl( sharedBufferID, IPC_RMID, NULL ); exit( 1 ); } /* Initialize the shared memory. */ strcpy( pSharedBuffer, "Mom, there's a singing moose outside!\n" ); printf( "%s", pSharedBuffer ); /* Fork a child process */ pid = fork(); if( pid == -1 ) { perror( "fork() failure" ); } else if( pid != 0 ) { printf( "The parent %d is waiting.\n", getpid() ); wait( &status ); printf( "The state of affairs is: %s\n", pSharedBuffer ); } else { printf( "The child %d is ready to shoo the moose away.\n", getpid() ); strcpy( pSharedBuffer, "The moose is gone now." ); } printf( "%d is quitting\n", getpid() ); fflush( stdout ); /* Clean up the shared memory. */ shmctl( sharedBufferID, IPC_RMID, NULL ); shmdt( pSharedBuffer ); return( 0 ); }