#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <stdio.h>
usingnamespace std;
bool primeCheck(int, char* argv[]);
void fillArray(char* argv[], int numbers[]); //function declerations
int main(int argc, char* argv[])
{
clock_t startTime = clock();
int numbers[*argv[0]]; //this is the global array for the random numbers
int prime = 0; //these two are used for storing the amount of primes/not primes
int notPrime = 0;
int pid; //this will be filled with the process id for the child
pid = fork(); //the pid is here assigned and a new process is started
if (getpid() == pid)
{ //if this is the child
srand(*argv[2]); //set its seed to child
}
else
{ //else
srand(*argv[1]); //set seed to parent
}
fillArray(*argv[0]); //fill the global array with different seeds
for (int i = 0; i<*argv[0]; i++)
{ //for the amount of random numbers.
if (primeCheck())
{ //check if its prime
prime++; //if its prime, increase it
}
else
{ //else
notPrime++; //count up not prime
}
}
clock_t endTime = clock();
clock_t clockTicks = endTime - startTime;
double timeSec = clockTicks / (double)CLOCKS_PER_SEC;
if (pid == 0)
{
// child
cout << "C; ID: " << getpid() << " Prime: " << prime << " Not Prime: " << notPrime << "CPU Time: " << timeSec << endl;
exit(1);
}
else
{ //parent
cout << "P; ID: " << getpid() << " Prime: " << prime << " Not Prime: " << notPrime << "CPU Time: " << timeSec << endl;
}
return 0;
}
void fillArray(char* argv[], int numbers[]) //fills array with random numbers
{
int count = *argv[0];
int i = 0;
for (int i = 0; i<count; i++)
{
numbers[i] = rand();
}
}
bool primeCheck(int number, char* argv[]) //goes through array to check numbers
{
int i = 2;
while (i < (number / 2))
{
if (number % i == 0)
{
returnfalse;
}
++i;
}
if (i == (number / 2))
{
returntrue;
}
}
First off, please don't double-post. I know this is a bit of a gray area since there are some Unix specific ideas, but your main problem is not the Unix code but instead c++ basics.
If you look into what the argv[] in main(int argc, char * argv[]) actually is then you can rewrite your code to make more sense. Especially you need to look into parsing from a char string into an int. A quick google search should get you there. Perhaps also research a bit deeper into pointers and arrays.
There's enough conceptually wrong with this code that you might need to start over from scratch once that research is done, that might be the easiest way. If you choose that route then test your code as often as possible to catch errors before they become intrinsic in the code.
People in the beginner's forums won't steer you wrong, and there is a much larger pool of people in those forums.