Programming Interfaces Guide

Attaching and Detaching a Shared Memory Segment

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

#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("shmat failed");
                nap–-;
        } else
                (void) fprintf(stderr, "shmop: shmat returned %p\n",
                                    p–>shmaddr);
        ...
        i = shmdt(addr);
        if(i == –1) {
                 perror("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];
                 }
        }
...