/* sharedmem.c Started by Jeff Ondich on 4/11/96 Last modified on 4/7/10 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!" ); fprintf( stdout, "[Parent:%d before fork] Buffer: '%s'\n", getpid(), sharedBuffer ); /* Fork a child process */ pid = fork(); if( pid == -1 ) { perror( "fork() failure" ); } else if( pid != 0 ) { fprintf( stdout, "[Parent:%d] Waiting...\n", getpid() ); wait( &status ); fprintf( stdout, "[Parent:%d] Done waiting. Buffer: '%s'\n", getpid(), sharedBuffer ); fprintf( stdout, "[Parent:%d] Quitting\n", getpid() ); } else { fprintf( stdout, "[Child:%d] Changing the buffer.\n", getpid() ); strcpy( sharedBuffer, "The moose is gone now." ); fprintf( stdout, "[Child:%d] Buffer: '%s'\n", getpid(), sharedBuffer ); fprintf( stdout, "[Child:%d] Quitting\n", getpid() ); } /* Clean up the shared memory. */ shmdt( sharedBuffer ); shmctl( sharedBufferID, IPC_RMID, NULL ); return 0; }