ptg10805159
574 Interprocess Communication Chapter 15
Once a shared memory segment has been created, a process attaches it to its address
space by callingshmat.
#include <sys/shm.h>
void *shmat(intshmid,const void *addr,intflag);
Returns: pointer to shared memory segment if OK,−1 on error
The address in the calling process at which the segment is attached depends on theaddr
argument and whether theSHM_RNDbit is specified inflag.
•Ifaddris 0, the segment is attached at the first available address selected by the
kernel. This is the recommended technique.
•Ifaddris nonzeroandSHM_RNDis not specified, the segment is attached at the
address given byaddr.
•Ifaddris nonzeroandSHM_RNDis specified, the segment is attached at the
address given by (addr− (addrmodulusSHMLBA)). TheSHM_RNDcommand
stands for ‘‘round.’’SHMLBAstands for ‘‘low boundary address multiple’’and is
always a power of 2. What the arithmetic does is round the address down to the
next multiple ofSHMLBA.
Unless we plan to run the application on only a single type of hardware(which is
highly unlikely today), we should not specify the address wherethe segment is to be
attached. Instead, we should specify anaddrof 0 and let the system choose the address.
If theSHM_RDONLYbit is specified inflag,the segment is attached as read-only.
Otherwise, the segment is attached as read–write.
The value returned byshmatis the address at which the segment is attached, or− 1
if an error occurred. Ifshmatsucceeds, the kernel will increment theshm_nattch
counter in theshmid_dsstructureassociated with the shared memory segment.
When we’redone with a shared memory segment, we callshmdtto detach it. Note
that this does not remove the identifier and its associated data structurefromthe
system. The identifier remains in existence until some process (often a server)
specifically removes it by callingshmctlwith a command ofIPC_RMID.
#include <sys/shm.h>
int shmdt(const void *addr);
Returns: 0 if OK,−1 on error
Theaddrargument is the value that was returned by a previous call toshmat.If
successful,shmdtwill decrement theshm_nattchcounter in the associatedshmid_ds
structure.
Example
Whereakernel places shared memory segments that areattached with an address of 0
is highly system dependent. Figure15.31 shows a program that prints some
information on whereone particular system places various types of data.