我想在C中使用叉進行計算。 我有一個包含成員{1,2,3,4}的二維數組,我有一個函數來獲取每個成員的平方陣列。我將用子進程調用這個函數。 例如對於3個子進程的輸出將會是這樣的;傳遞二維數組遞歸
1.Child
1 4
9 16
----------
2.Child
1 16
81 256
----------
3.Child
1 256
6561 65536
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int matrix[2][2] = {1, 2, 3 ,4 } ;
int main(){
forkFork(3);
}
void forkFork(int counter)
{
pid_t pid;
if(counter == 0)
{
exit(0);
}
if(counter > 0)
{
if ((pid = fork()) < 0)
{
perror("fork error :(");
}
else if (pid == 0)
{
matrixPower(matrix);
print(matrix);
}
else if(pid > 0)
{
forkFork(counter - 1);
}
}
}
void matrixPower(int m[2][2])
{
int i,j,k;
int result = 0;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
result = matrix[i][j]*matrix[i][j];
m[i][j] = result;
result = 0;
}
}
}
void print(int a[2][2])
{
int row, col ;
for( row = 0; row < 2; row++)
{
for( col = 0; col < 2 ; col++)
{
printf("%d\t", a[row][col]);
}
puts("");
}
printf("-------------------------------\n");
}
我不能找到一種方法,通過新的數組遞歸函數...
通過'forkFork'函數作爲參數傳遞數組有什麼問題? – hmatar
它沒有傳遞新的價值;例如在forkFork的第一次調用時,矩陣數組更改爲{1,4,9,16} 在第二個進程調用中(使用遞歸),我試圖將{1,4,9,16}傳遞給forkFork函數,但它使用舊值{1,2,3,4} – hkn
我發現了這個問題,並在下面提供了一個解決方案。 – hmatar