#!/usr/bin/perl
#*******************************************
#Student name: Davina Chin Lee Yien
#Student Id: 7D2A1001
#SPD251 Assignment 2 Question 3
#*******************************************

#Problem: The random number cannot add..how ???

use warnings;
use strict;
#declare the variable
my ($pid, $pid2, $times,$count);
my ($c,$no1,$tot);

$times=@ARGV;
if ($times==0){
	die "No arguments!\n";

}
#check to see if the value enter is from 0-9..which is single digit number
if ($times = shift){
 if (($times!=0)&&($times!=1)&&($times!=2)&&($times!=3)&&($times!=4)&&($times!=5)&&($times!=6)&&($times!=7)&&($times!=8)&&($times!=9)){
	print "Enter single digit number!!\n";
	exit();
 }
}

#intialize the value
$tot=0;
$no1=0;
$count =0;

#to create number of child process according to the $times
while ($count != $times){
$count ++;
if ($pid=fork()) {
	#this is for parent
	print "Parent producing child process $count\n";
	sleep(2);
	print "Wait for kids\n";
	#waits for all the children of a particular process to finish before allowing the parent process to continue its execution
	my $straggler = wait();
	#parent finish when all the child process finish
	if($count == $times){
		print "Finally $straggler finish\n";
		print "Parent finish\n";
	}
}
else {
	if (defined ($pid)){
		#creating new process......
		sleep ( 1 );
		print ("Kid ", $count," Executing\n");
		#generating a random number for each process
		$no1=1+int(rand(10));
		print "Random number generated by child process : $no1\n";
		$c=0;
		$tot=0;
		while($c!=$no1+1){
			$tot=$tot+$c;
			$c++;
		}
		print "\nTotal from the random number are:  $tot\n";
		#$tot=$tot+$no1;
		sleep( 2 );
		print "Kid $count : Finish\n";
		exit();
	}
	else{
		#cannot fork
		die ("Forking problems");
	}
}

}
