/* sharedmem.c Started by Jeff Ondich on 4/11/96 Last modified on 3/31/04 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 ) { pid_t pid; int status; char *sharedBuffer; 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. */ sharedBuffer = (char *)shmat( sharedBufferID, (char *)0, 0 ); if( sharedBuffer == (char *)-1 ) { perror( "Shmat trouble" ); shmctl( sharedBufferID, IPC_RMID, NULL ); exit( 1 ); } /* Initialize the shared memory. */ strcpy( sharedBuffer, "Mom, there's a singing moose outside!\n" ); printf( "%s", sharedBuffer ); /* 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", sharedBuffer ); } else { printf( "The child %d is ready to scare the moose away.\n", getpid() ); strcpy( sharedBuffer, "The moose is gone now." ); } printf( "%d is quitting\n", getpid() ); fflush( stdout ); /* Clean up the shared memory. */ shmdt( sharedBuffer ); shmctl( sharedBufferID, IPC_RMID, NULL ); return( 0 ); }