Attaching and Detaching a Shared Memory Segment

shmat() and shmdt() functions 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. For more information, see the shmop(2), shmat(2), and shmdt(2) man pages.

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("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];
                 }
        }
...