/* Using shared memory mechanism */

#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/times.h>
#include <limits.h>
#include <fcntl.h>
#include <stdio.h>
#include "Lib.c"

typedef struct Record{

       int dum[1000];
}RECORD;

int
main(int argc, char **argv)
{
	int n;
	int i;
	int j;
	int fd;
	int pid;
	RECORD zero;
	RECORD *ptr;
	myTime mytime;
	struct tms buffer;
	long realtime;


	realtime = times(&buffer);
 	printf("\n   o Real Time is %ld", realtime);          
 	printf("\n   o System Level Time is %ld", buffer.tms_stime);          
 	printf("\n   o User Level Time is %ld", buffer.tms_utime);          
 	printf("\n   o Child System Level Time is %ld", buffer.tms_cstime);             printf("\n   o Child User Level Time is %ld", buffer.tms_cutime);          

	if (argc != 2){
		fprintf(stdout, "\n usage: s <number>\n");
		exit(0);
	}

	n = atoi(argv[1]);

	fd = open("m", O_RDWR | O_CREAT);
	write(fd, &zero, sizeof(RECORD));

	ptr = (RECORD *) mmap(NULL, sizeof(RECORD)*n, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	close(fd);

	setbuf(stdout, NULL);


	if(pid = fork() == 0){ /* Child */

	   BeginTiming(0);

	   for (i = 0; i < n; i++){
		for (j = 0; j < 1000; j++)
		     	ptr->dum[j] = 0;
		ptr++;
	   }

           mytime = EndTiming(0);

           printf("\n Running time accounted as follows: ");                                             
	   printf("\n   o System Level running time of thread creation is %lf", mytime.stime);          
	   printf("\n   o User Level running time of thread creation is %lf\n", mytime.utime);                   

	   exit(0);
	}

	waitpid(pid, NULL, 0);

	realtime = times(&buffer);
 	printf("\n   o Real Time is %ld", realtime);          
 	printf("\n   o System Level Time is %ld", buffer.tms_stime);          
 	printf("\n   o User Level Time is %ld", buffer.tms_utime);          
 	printf("\n   o Child System Level Time is %ld", buffer.tms_cstime);             printf("\n   o Child User Level Time is %ld", buffer.tms_cutime);          

	return 1;
}
