/* sharedint.c - A process forks. The child will ask interactively an integer from the user, store it in shared memory, and then terminate. The parent will wait for the child to terminate, read the integer from shared memory and print it out. It is all fairly easy since the identity of the shared segment as created by the parent is inherited by the child. */ #include #include #include #include #include #include #include #define SHM_MODE (SHM_R | SHM_W) /* user read/write */ int main(void) { int shmid; char *shmptr; int *p, *q; pid_t pid, npid; int statusloc; /* allocate ipc key in parent for a small shared segment*/ if ( (shmid = shmget(IPC_PRIVATE, sizeof(int), SHM_MODE)) < 0) { perror("shmget failure"); exit(1);} /* create child; it inherits the ipc key from parent */ if ((pid = fork()) < 0) { perror("fork failure"); exit(1);} else if (pid == 0) { /* child */ /* attach to shared area and read an integer */ if ( (shmptr = (char *)shmat(shmid, 0, 0)) == (void *) -1) { perror("shmat failure in child"); exit(1);} p = (int *)shmptr; printf("Enter an integer: "); scanf("%d", p); /* detach from the shared memory */ if (shmdt(shmptr) < 0) { perror("shmdt"); exit(1);} exit(0);} else { /* parent */ /* in the parent attach the shared area and write the integer */ /* that was read by the child into the shared area. */ if ( (shmptr = (char *)shmat(shmid, 0, 0)) == (void *) -1) { perror("shmat failure in parent"); exit(1);} q = (int *)shmptr; /* we wait for child to terminate and then print */ while((npid=waitpid(pid,&statusloc,0))!=pid) { printf("The child did not terminate yet!\n"); } printf("The number was %d\n", *q); /* detach from the shared memory */ if (shmdt(shmptr) < 0) { perror("shmdt"); exit(1);} /* release the shared memory */ if (shmctl(shmid, IPC_RMID, 0) < 0) { perror("shmctl"); exit(1);} } return (0); }