I need to get the outputs of each process to strictly alternate. however after i select which process to out put first my program gets stuck. Any help would be much appreciated i have been stuck for awhile. code follows.
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include <ctime>
using namespace std;
int main()
{
bool flag [2];
flag [0] = true;
flag [1] = true;
int pid;
int randomnums;
string whofirst;// input for first process to cout
int turn = 0;
time_t Btime1, Btime2, Etime1, Etime2; // time pointers
srand(time(NULL));// random number seed
cout << "How many numbers should i generate?";
cin >> randomnums;
cout << "Who should I let output first? parent or child? " ;
cin >> whofirst;
if(whofirst == "child")
{
turn = 0;
}
else
{
turn = 1;
}
pid = fork();// process forking in two
if (pid == 0)
{
// Child process
time( &Btime1);// process start time
for(int index = 0; index < randomnums; index++) // random number loop
{
flag[0] = true;
while(flag[1] == true && turn == 1)
{
}
cout << "\n I am the child; my ID = " << getpid() << " Random Number: " << rand() % 100 << endl;
flag[0] = false;
turn = 1;
}
time( &Etime1);// process end time
cout << "\n I am the child; my ID = " << getpid() << " Begin Time: " << ctime (&Btime1)<< " End Time: " << ctime (&Etime1) << endl;
exit(0);
}
else
{ // Parent process
time( &Btime2); // process start time
srand(time(NULL)); //random seeding based on current time
for(int count = 0; count < randomnums; count++)// random number loop
{
flag[1] = true;
while(flag[0] == true && turn == 0)
{
}
cout << "\n I am the parent; my ID = " << getpid() << " Random Number: " << rand() % 100 << endl;
flag[1] = false;
turn = 0;
}
time( &Etime2);// process end time
cout << "\n I am the parent; my ID = " << getpid() << " Begin Time: " << ctime (&Btime2)<< " End Time: " << ctime (&Etime2) << endl;
exit(0);
}
}