我使用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之上''可能有帮助吗? –