I am trying to complete a tutorial on running a parallel programme in C using fork() and execl commands.
The user enters the number of inputs(N). The next N lines contain a number <= 10 digits. My programme will calculate the number of prime factors for each digit.
I am trying to make the execution of the lines parallel using fork and execl.
Parallel.c
int main() {
int userInput, childPid, childResult, number;
//Since largest number is 10 digits, a 12 characters string is more
//than enough
char cStringExample[12];
scanf("%d", &userInput);
for (int i = 0; i < userInput; i++) {
scanf("%d",&number);
childPid = fork();
if (childPid == 0) {
sprintf(cStringExample,"%d",number);
execl("./PF","PF",cStringExample,NULL);
}
}
while (wait(&childResult) != -1) {
printf("%d has %d prime factors\n",number,childResult >> 8);
}
}
PrimeFactorization.c
int main( int argc, char* argv[]) {
int nFactor = 0, userInput, factor;
//Convert string to number
userInput = atoi( argv[1] );
nFactor = 0;
factor = 2;
//quick hack to get the number of prime factors
// only for positive integer
while (userInput > 1){
if (userInput % factor == 0){
userInput /= factor;
nFactor++;
} else {
factor++;
}
}
// printf("%d has %d prime factors\n",userInput,nFactor);
return nFactor;
}
I want to be able to print for each forked() process the number that was inputted into the Prime Factorisation programme as well as the number of prime factors for it. For example if I input
5
44721359
99999989
9
111113111
118689518
the output is
118689518 has 2 prime factors
118689518 has 3 prime factors
118689518 has 1 prime factors
118689518 has 1 prime factors
118689518 has 1 prime factors
The prime factors are correct just that it does not correspond to the number that has been inputted. How am I able to do that? I tried to insert the wait command inside the for loop but I don't think that produces parallelism. I understand why it gives me the output but I can't think of a solution for it.