这是一个简单的 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;
}
从来没有听说过段错误,有人可以解释一下它是什么意思吗?
最佳答案
这个:
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++ )
关于c - 并行程序中的 GCC 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15053180/