VMS Help  —  CRTL  Shared Memory Routines, Example
        /*
        Abstract: This test program creates a Shared Memory Segment,
        writes data to the segment then reads the data after attaching again.
        It also ensures that an EINVAL error is generated when trying to attach
        a memory segment that has already been deleted.
        */
        #include <errno.h>
        #include <types.h>
        #include <ipc.h>
        #include <shm.h>
        #include <stdio.h>
        #include <stdlib.h>
        #include <string.h>
        #define SHMSZ 128
        #define SHMKEY 9229

        main()
        {
            int shmid;
            char *shm_write;
            char *shm_read;

            printf("Creating Shared Memory Segment\n");
            if ((shmid = shmget(SHMKEY, SHMSZ, IPC_CREAT | 0666)) < 0)
            {
                perror("shmget");
                printf("\nshmget(): FAILED\n");
            }
            if ((shm_write = shmat(shmid, NULL, 0)) == (char *) -1)
            {
                perror("shmat");
                printf("\nshmat(): FAILED\n");
                return;
            }
            printf("Writing Data to the Created Shared Memory Segment\n\n");
            memcpy(shm_write, "Test Shared Memory Segment", SHMSZ);
            printf("Detaching Shared Memory Segment\n");
            if( shmdt(shm_write)<0)
                perror("shmdt");

            printf("Attach again to read the data from Shared Memory Segment\n\n");
            if ((shm_read = shmat(shmid, NULL, 0)) == (char *) -1)
            {
                perror("shmat");
                printf("\nshmat(): FAILED\n");
            }
            printf("Reding Data from Shared Memory Segment\n");
            printf("Data in Segment is: %s\n\n",shm_read);

            printf("Detaching Shared Memory Segment\n");
            if( shmdt(shm_read)<0)
                perror("shmdt");
            printf("Deleting Shared Memory Segment using IPC_RMID\n\n");
            if( shmctl(shmid, IPC_RMID, NULL)<0)
                perror("shmctl");
            printf("Attaching to the deleted Shared Memory Segment - error EINVAL should be generated\n\n");
            if ((shm_write = shmat(shmid, NULL, 0)) == (char *) -1)
                perror("shmat");
        }

        This example produces the following output:

            Creating Shared Memory Segment
            Writing Data to the Created Shared Memory Segment

            Detaching Shared Memory Segment
            Attach again to read the data from Shared Memory Segment

            Reding Data from Shared Memory Segment
            Data in Segment is: Test Shared Memory Segment

            Detaching Shared Memory Segment
            Deleting Shared Memory Segment using IPC_RMID

            Attaching to the deleted Shared Memory Segment - error EINVAL should be generated

            shmat: invalid argument
Close Help