我正在尝试完成有关使用fork()和execl命令在C中运行并行程序的教程。
用户输入输入数(N)。接下来的N行包含一个<= 10位数字。我的程序将计算每个数字的质因子数。
我正在尝试使用fork和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;
}
我希望能够为每个forkd()进程打印输入到Prime Factorisation程序中的数字以及其质数的数量。 例如,如果我输入
5
44721359
99999989
9
111113111
118689518
输出为
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
主要因素是正确的,只是它与输入的数字不对应。我该怎么做?我试图将wait命令插入for循环内,但我认为不会产生并行性。我知道为什么它会给我输出,但我想不出解决方案。