#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
int main( int argc, char **argv) {
pid_t pid;
hrtime_t startTime, endTime;
int numberOfRandoms, whoGoesFirst;
int PA[2]; // pipe A
int PB[2]; // pipe B
char msg[80]; // buffer to hold message
pipe(PA); // create the IPC pipe
pipe(PB); // create the IPC pipe
/* fork a child process */
if ( argc < 2) {
printf(" usage: a.out #randNums whofirst 0=Parent, 1=child\n");
exit(1);
}
numberOfRandoms = atoi( argv[1] );
whoGoesFirst = atoi( argv[2] );
startTime = gethrtime();
pid = fork();
if (pid == 0) { /* child process */
startTime = gethrtime();
pid = getpid();
printf("---->Child: Hello pid: %d \n", pid);
write(PB[1], "GO",3);
read(PA[0], msg,3);
if ( whoGoesFirst==0) { // parent
for ( int i=1; i <= numberOfRandoms; i++) {
read(PA[0], msg, 3); // wait for "GO"
printf(" Child: number is %d \n", rand() );
write(PB[1], "GO",3); // send " Your turn "
}
}
else {
for ( int i=1; i <= numberOfRandoms; i++) {
printf(" Child: number is %d \n", rand() );
write(PB[1], "GO",3); // send "Your turn"
read(PA[0], msg, 3); // wait for "GO"
}
}
endTime = gethrtime();
printf("Child is done start: %lld end: %lld\n",startTime,endTime);
write(PB[1], "GO",3);
} else { /* parent process */
pid = getpid();
printf("----->Parent: Hello pid: %d \n", pid);
write(PA[1], "GO",3);
read(PB[0], msg,3);
if ( whoGoesFirst==1) { // parent
for ( int i=1; i <= numberOfRandoms; i++) {
read(PB[0], msg, 3);
printf(" Parent: number is %d \n", rand() );
write(PA[1], "GO",3);
}
}
else {
for ( int i=1; i <= numberOfRandoms; i++) {
printf(" Parent: number is %d \n", rand() );
write(PA[1], "GO",3);
read(PB[0], msg, 3);
}
}
endTime = gethrtime();
printf("Parent is done start: %lld end: %lld\n",startTime,endTime);
write(PA[1],"GO",3);
}
}
The challenge is now to use semaphores to interleave the outputs and share generated data with the other process and the last process destroys the semaphores. What would be the best way of attacking this? Obviously the topic because discussed now in class is semaphores so I have no prior experience with them.
Thanks
This post has been edited by skatingrocker17: 08 October 2012 - 06:27 AM

New Topic/Question
Reply



MultiQuote




|