Creating a shared memory segment with the shmat subroutine

This section describes how to create a shared memory segment with the shmat subroutine

Prerequisite tasks or conditions

None.

Procedure

  1. 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 );
  2. 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 | 0666 );
    • 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 );
  3. 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, 0, 0 );
    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.
  4. Work with the data in the segment using the template structure.
  5. Detach from the segment using the shmdt subroutine:
    shmdt( ptr );
  6. 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.