我使用fork()創建子進程。由於子進程從父進程繼承數據,因此我在父進程中創建了一個數組,並在子進程內調用了一個計算函數,該函數計算數組中所有具有奇數索引的元素的總和。它給了我一個錯誤...子進程如何使用fork()從父進程繼承數據?
Conrados-MBP:oshw3 conrados$ make
g++ -c -Werror main.cc
main.cc:33:18: error: use of undeclared identifier 'arr'
int sum = calc(arr);
如果子進程繼承的數據,在這種情況下,陣「改編」父類中,那麼爲什麼它給我這個錯誤?我的代碼如下。
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
/*
calculate the production of all elements with odd index inside the array
*/
int calc(int arr[10]) {
int i=0;
int sum = 0;
for (i=1; i<10; i=i+2) {
sum = sum + arr[i];
}
return sum;
} // end of calc
int main() {
pid_t pid;
/* fork a child process */
pid = fork();
if (pid < 0) { /* error occurred */
fprintf(stderr, "Fork Failed\n");
return 1;
}
else if (pid == 0) { /* child process */
printf("I am the child process\n");
// the child process will calculate the production
// of all elements with odd index inside the array
int sum = calc(arr);
printf("sum is %d\n", sum);
_exit(0);
}
else { /* parent process */
/* parent will wait for the child to complete */
printf("I am the parent, waiting for the child to end\n");
// the parent process will create an array with at least 10 element
int arr[] = { 1, 2, 5, 5, 6, 4, 8, 9, 23, 45 };
wait(NULL);
}
return 0;
} // end of main
閱讀http://advancedlinuxprogramming.com/;在上面的程序中,使用'exit'(而不是'_exit'),否則標準輸出將不會正確刷新。解釋'fork'可能需要整本書(或其中的幾章)。 –
'fork'不會奇蹟般地改變C++的範圍規則。 – melpomene
也許移動'int arr [] = ...'在pid_t pid之上''可能有幫助嗎? –