#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>

#define SEGSIZE 100

void
readshm(int shmid, char *segptr, int sleep_period)
{
        printf("%s\n", segptr);
        sleep(sleep_period);
        //printf("segptr: %s\n", segptr);
        printf("%s\n", segptr);
}

void
usage()
{
        fprintf(stderr, "shmread - A utility to read from shared memory\n");
        fprintf(stderr, "\nUSAGE:  shmread <id> <pause>\n");
        exit(1);
}

int
main(int argc, char *argv[])
{
        key_t key;
        int   shmid;
        char  *segptr;

        if(argc == 1)
                usage();

        /* Create unique key via call to ftok() */
        key = ftok(".", atoi(argv[1]));

        /* Open the shared memory segment - create if necessary */
        if((shmid = shmget(key, SEGSIZE, IPC_CREAT|IPC_EXCL|0666)) == -1) 
        {
                //printf("Shared memory segment exists - opening as client\n");

                /* Segment probably already exists - try as a client */
                if((shmid = shmget(key, SEGSIZE, 0)) == -1) 
                {
                        perror("shmget");
                        exit(1);
                }
        }
        else
        {
                //printf("Creating new shared memory segment\n");
        }

        /* Attach (map) the shared memory segment into the current process */
        if((segptr = (char *)shmat(shmid, 0, 0)) == (char *)-1)
        {
                perror("shmat");
                exit(1);
        }

        readshm(shmid, segptr, atoi(argv[2]));

	exit(EXIT_SUCCESS);
}
