System Interface Guide

Attaching and Detaching a Shared Memory Segment

shmat() and shmdt() (see shmop(2)) are used to attach and detach shared memory segments. shmat() returns a pointer to the head of the shared segment. shmdt() detaches the shared memory segment located at the address indicated by shmaddr. The following code illustrates calls to shmat() and shmdt():


#include			<sys/types.h>
 #include			<sys/ipc.h>
 #include			<sys/shm.h>

 static struct state					{	/* Internal record of attached segments. */
 	int		shmid;			/* shmid of attached segment */
 	char		*shmaddr;			/* attach point */
 	int		shmflg;			/* flags used on attach */
 	ap[MAXnap];					/* State of current attached segments. */
 	int		nap;			/* Number of currently attached segments. */
 ...
 	char				*addr;			/* address work variable */
 	register int				i;			/* work area */
 	register struct state			*p;				/* ptr to current state entry */
 ...
 	p = &ap[nap++];
 	p->shmid = ...
 	p->shmaddr = ...
 	p->shmflg = ...
 	p->shmaddr = shmat(p->shmid, p->shmaddr, p->shmflg);
 	if(p->shmaddr == (char *)-1) {
 		perror("shmop: shmat failed");
 		nap--;
 	} else
 		 (void) fprintf(stderr, "shmop: shmat returned %#8.8x\n",
 					p->shmaddr);
 	...
 	i = shmdt(addr);
 	if(i == -1) {
 		perror("shmop: shmdt failed");
 	} else {
 		(void) fprintf(stderr, "shmop: shmdt returned %d\n", i);
 		for (p = ap, i = nap; i--; p++) {
 			if (p->shmaddr == addr) *p = ap[--nap];
 		}
 	}
 	...