/* Program to demonstrate shared memory IPC */ /* Written by Carey Williamson Jan 27, 2010 */ #include #include #include #include #include #include #include #include #define DEBUG 1 #define SLOW 1 int main() { pid_t pid; int i, num = 0; int segmentid; void *memptr; /* create a shared memory region */ segmentid = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0777); /* check return value */ if( segmentid == -1 ) printf("Failed to allocate shared memory segment!\n"); else printf("Allocated a shared memory segment (%d)\n", segmentid); /* fork a child process */ pid = fork(); if( pid < 0 ) { /* error occurred */ fprintf(stderr, "Fork failed!\n"); return 1; } else if( pid == 0 ) { /* child process */ #ifdef DEBUG printf("\t\t\t\tI am the child! Here I go...\n"); #endif /* attach shared memory segment within process address space */ memptr = (void *)shmat(segmentid, NULL, 0); /* check return value */ if( memptr == (void *) -1 ) printf("\t\t\t\tChild failed to attach shared memory segment! %d\n", errno); else printf("\t\t\t\tChild process: memptr = %x\n", memptr); #ifdef SLOW sleep(1); #endif printf("\t\t\t\tChild process views msg = %s\n", memptr); sprintf(memptr, "Hello 1 from child"); printf("\t\t\t\tChild process sets msg = %s\n", memptr); #ifdef SLOW sleep(3); #endif printf("\t\t\t\tChild process views msg = %s\n", memptr); sprintf(memptr, "Hello 2 from child"); printf("\t\t\t\tChild process sets msg = %s\n", memptr); #ifdef SLOW sleep(5); #endif printf("\t\t\t\tChild process views msg = %s\n", memptr); sprintf(memptr, "Hello 3 from child"); printf("\t\t\t\tChild process sets msg = %s\n", memptr); #ifdef SLOW sleep(7); #endif /* detach shared memory segment from process address space */ shmdt(memptr); printf("\t\t\t\tThat was fun! All done now.\n"); } else { /* parent process */ #ifdef DEBUG printf("I am the parent!\n"); #endif /* attach shared memory segment within process address space */ memptr = (void *)shmat(segmentid, NULL, 0); /* check return value */ if( memptr == (void *) -1 ) printf("Parent failed to attach shared memory segment! %d\n", errno); else printf("Parent process: memptr = %x\n", memptr); #ifdef SLOW sleep(2); #endif printf("Parent process views msg = %s\n", memptr); sprintf(memptr, "Hello 1 from parent"); printf("Parent process sets msg = %s\n", memptr); #ifdef SLOW sleep(4); #endif printf("Parent process views msg = %s\n", memptr); sprintf(memptr, "Hello 2 from parent"); printf("Parent process sets msg = %s\n", memptr); #ifdef DEBUG printf("Waiting for child now...\n"); #endif wait(NULL); /* detach shared memory segment from process address space */ shmdt(memptr); #ifdef DEBUG printf("All done, and my child too!\n"); #endif } }