#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

/* An illustration of how System V shared memory works.  
 */

struct data {
    int id;
    int num;
};


main() {
    int id, i, pid;
    int size = 0x5000; /* 20 kbytes */
    int flags = (SHM_R |SHM_W);
    struct data *daddr;
    int stat;

    id = shmget(IPC_PRIVATE, size, flags | IPC_CREAT);
    if(id == -1) 
	perror("shmget:");

    
    pid = fork();
    if( pid == 0 ) {  /* child will add data to the shared memory */
	daddr = shmat(id, 0, 0);
	if(daddr == (struct data *)-1) 
	    perror("shmat:");
	
	for(i = 0; i < 10 ; i++) {
	    daddr[i].id = i;
	    daddr[i].num = i * 10;
	}
	shmdt(daddr);
    }
    else { /* parent prints out data from the shared memory */
	daddr = shmat(id, 0, 0);
	if(daddr == (struct data *)-1) 
	    perror("shmat:");
	wait(&stat);

	for(i = 0; i < 10 ; i++) {
	    fprintf(stdout, "%d %d\n", daddr[i].id, daddr[i].num);
	}

	/* clean up shared memory segment */
	shmdt(daddr);
	shmctl(id, IPC_RMID, NULL);
    }

    
}
