#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
copyshm(char *dest, char *src)
{
	strcpy(dest, src);
}

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

int
main(int argc, char *argv[])
{
        key_t key1, key2;
        int   shmid1, shmid2;
        char  *segptr1, *segptr2;

        if(argc == 1)
                usage();

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

        if((shmid1 = shmget(key1, SEGSIZE, IPC_CREAT|IPC_EXCL|0666)) == -1) 
        {
                if((shmid1 = shmget(key1, SEGSIZE, 0)) == -1) 
                {
                        perror("shmget");
                        exit(1);
                }
        }

        if((shmid2 = shmget(key2, SEGSIZE, IPC_CREAT|IPC_EXCL|0666)) == -1) 
        {
                if((shmid2 = shmget(key2, SEGSIZE, 0)) == -1) 
                {
                        perror("shmget");
                        exit(1);
                }
        }

        if((segptr1 = (char *)shmat(shmid1, 0, 0)) == (char *)-1)
        {
                perror("shmat");
                exit(1);
        }

        if((segptr2 = (char *)shmat(shmid2, 0, 0)) == (char *)-1)
        {
                perror("shmat");
                exit(1);
        }

	sleep(atoi(argv[3]));

        copyshm(segptr2, segptr1);

	exit(EXIT_SUCCESS);
}
