8 /* return a pointer to a anonymous shared memory segment of size "size"
9 which will persist across fork() but will disappear when all processes
11 The memory is not zeroed
13 void *shm_setup(int size)
18 shmid = shmget(IPC_PRIVATE, size, SHM_R | SHM_W);
20 printf("can't get shared memory\n");
23 ret = (void *)shmat(shmid, 0, 0);
24 if (!ret || ret == (void *)-1) {
25 printf("can't attach to shared memory\n");
29 /* the following releases the ipc, but note that this process
30 and all its children will still have access to the memory, its
31 just that the shmid is no longer valid for other shm calls. This
32 means we don't leave behind lots of shm segments after we exit */
33 shmctl(shmid, IPC_RMID, 0);
40 int main(int argc, char *argv[])
46 printf("shm_sample <size>\n");
52 buf = shm_setup(size);
55 printf("shm_setup(%d) failed\n", size);
62 /* now just to show it worked we will put the pid of the child
63 at the start of the shared memory segment and read it from
68 while (*(int *)buf == 0) ;
69 printf("pid via shm is %d real pid is %d\n",
70 *(int *)buf, getpid());