Interprocess communication

Operations for shared memory

This section describes how to use the shmat and shmdt system calls. The accompanying program illustrates their use.

Using shared memory operations: shmat and shmdt

The synopsis found on the shmop(2) manual page is as follows:

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

void *shmat (shmid, shmaddr, shmflg) int shmid; void *shmaddr; int shmflg;

int shmdt (shmaddr) void *shmaddr;

Attaching a shared memory segment

The shmat system call requires three arguments to be passed to it. It returns a character pointer value. Upon successful completion, this value will be the address in memory where the process is attached to the shared memory segment and when unsuccessful the value will be -1.

The shmid argument must be a valid, non-negative, integer value. In other words, it must have already been created by using the shmget system call.

The shmaddr argument can be zero or user supplied when passed to the shmat system call. If it is zero, the UNIX operating system picks the address where the shared memory segment will be attached. If it is user supplied, the address must be a valid address that the UNIX operating system could pick.

The following illustrates some typical address ranges.


Note that these addresses are in chunks of 20,000 hexadecimal. It would be wise to let the operating system pick addresses so as to improve portability.

The shmflg argument is used to pass the SHM_RND and SHM_RDONLY flags to the shmat system call.

Detaching shared memory segments

The shmdt system call requires one argument to be passed to it. It returns an integer value which will be zero for successful completion or -1 otherwise.

Further details on shmat and shmdt are discussed in the example program. If you need more information on the logic manipulations in this program, read ``Using shmget''. It goes into more detail than would be practical for every system call.

Next topic: Example program
Previous topic: shmctl system call example

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004