0

我正在尝试使用 fork() 和 execl 命令完成有关在 C 中运行并行程序的教程。

用户输入输入的数量(N)。接下来的 N 行包含一个 <= 10 位的数字。我的程序将计算每个数字的素数。

我正在尝试使用 fork 和 execl 并行执行行。

并行.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);
     }
}

质数分解.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;
}

我希望能够为每个 forked() 进程打印输入到素因子分解程序的数字以及它的素因子的数量。例如,如果我输入

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

质因数是正确的,只是它与输入的数字不对应。我怎么能做到这一点?我试图在 for 循环中插入等待命令,但我认为这不会产生并行性。我理解为什么它会给我输出,但我想不出解决方案。

4

0 回答 0