[ Previous |
Next |
Contents |
Glossary |
Home |
Search ]
AIX Version 4.3 General Programming Concepts: Writing and Debugging Programs
Creating a Shared Memory Segment with the shmat Subroutine
Prerequisite Tasks or Conditions
None.
Procedure
- Create a key to uniquely identify the shared segment. Use the ftok subroutine to create the key. For example, to create the key mykey
using a project ID of R
contained in the variable proj
(type char) and a file name of null_file
, use a statement like:
mykey = ftok( null_file, proj );
- Either:
- Create a shared memory segment with the shmget subroutine. For example, to create a shared segment that contains 4096 bytes and assign the shmid to an integer variable mem_id
, use a statement like:
mem_id = shmget(mykey, 4096, IPC_CREAT | o666 );
- Get a previously created shared segment with the shmget subroutine. For example, to get a shared segment that is already associated with the key mykey
and assign the shmid to an integer variable mem_id
, use a statement like:
mem_id = shmget( mykey, 4096, IPC_ACCESS );
- Attach the shared segment to the process with the shmat subroutine. For example, to attach a previously created segment, use a statement like:
ptr = shmat( mem_id );
In this example, the variable ptr
is a pointer to a structure that defines the fields in the shared segment. Use this template structure to store and retrieve data in the shared segment. This template should be the same for all processes using the segment.
- Work with the data in the segment using the template structure.
- Detach from the segment using the shmdt subroutine:
shmdt( ptr );
- If the shared segment is no longer needed, remove it from the system with the shmctl subroutine:
shmctl( mem_id, IPC_RMID, ptr );
Note: You can also use the ipcs command to get information about a segment, and the ipcrm command to remove a segment.
Related Information
Understanding Memory Mapping.
Mapping Shared Memory Segments with the shmat Subroutine.
Creating a Mapped Data File with the shmat Subroutine.
Creating a Copy-On-Write Mapped Data File with the shmat Subroutine.
The shmat subroutine, shmctl subroutine, shmdt subroutine, shmget subroutine.
[ Previous |
Next |
Contents |
Glossary |
Home |
Search ]