子进程如何使用fork()从父进程继承数据?
我使用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
就编译器而言,fork
只是一个正常的功能。
int sum = calc(arr);
在代码中的这一点上,在范围上没有arr
变量,所以你得到一个错误。
以另一种方式看,fork
创建了正在运行的进程的副本。在fork
处,父进程中没有arr
数组,所以子进程也不会有。 arr
只被创建以后,在fork
后:
// the parent process will create an array with at least 10 element
int arr[] = { 1, 2, 5, 5, 6, 4, 8, 9, 23, 45 };
如果您希望变量在这两个过程存在,则需要调用fork
之前创建它。
每个进程都有自己的虚拟地址空间。所以这两个变量不是“相同的”。 –
@BasileStarynkevitch是的,我说这是一个运行过程的副本。 – melpomene
阅读http://advancedlinuxprogramming.com/;在上面的程序中,使用'exit'(而不是'_exit'),否则标准输出将不会正确刷新。解释'fork'可能需要整本书(或其中的几章)。 –
'fork'不会奇迹般地改变C++的范围规则。 – melpomene
也许移动'int arr [] = ...'在pid_t pid之上''可能有帮助吗? –