-1

これは c の単純な並列プログラムです。

コンパイルにはubuntuとgccを使用しています。

プログラムはプロセス数の入力を受け取り、同じ数の数を作成してユーザーに要求します。次に、各プロセスを使用して、各数値の階乗を計算します。

#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>

int factorial(int n)
{
    int fact=1;
    int i;
    for(i=1 ; i<=n ; i++)
    {
        fact=fact*i;
    }
    return fact;
}

int main()
{
    int process_id;
    int num_process;
    int pid;
    int i;

    printf("\nEnter No. of Process : ");
    scanf("%d",&num_process);

    int num[num_process];

    for ( i=1; i < num_process; i++ )
    {
        printf("\nEnter %d Number : ",i);
        scanf("%d", &num[i]);
    }

    for ( i=0; i < num_process; i++ )
    {
        pid=fork();
        if (pid == -1)
        {
            perror("Error forking");
            return -1;
        }
        else if(pid > 0)
        {
            waitpid(-1, NULL, 0);
        }
        else
        {
            printf("\nFactorial of %d is : %d", num[i], factorial(num[i]));
            exit(0);
        }

    }
    return 0;
}

セグメンテーション違反について聞いたことがありませんが、誰かがそれが何を意味するのか説明できますか?

4

3 に答える 3

2

これ:

for ( i=1; i <= num_process; i++ )
{
    printf("\nEnter %d Number : ",i);
    scanf("%d", num[num_process]);
}

問題があります。の有効なインデックスnumは0からnum_process-1です。ループを次のように変更します。

for ( i=0; i < num_process; i++ )
于 2013-02-24T15:25:56.883 に答える
2

あなたのfactorial関数でfactは、初期化されていません。また

 scanf("%d", num[num_process]);

する必要があります

 scanf("%d", &num[num_process]);
于 2013-02-24T15:26:34.090 に答える
1

セグメンテーション違反の説明は、ここで読むことができます。

ここに障害があります:

   scanf("%d", num[num_process]);

あなたは1から数えているので - 配列はゼロから始まります

この行でfor ( i=0; i <= num_process; i++ )は、プロセスが多すぎます。

ALSO forkは別のプロセスを作成するため、プログラムは並列ではありません。スレッドを使用する必要があります。それをググってください。

于 2013-02-24T15:26:35.977 に答える