私はfork()を使って子プロセスを作成しています。子プロセスは親プロセスからデータを継承するので、親プロセスで配列を作成し、配列内の奇数インデックスを持つすべての要素の合計を計算する子プロセス内でcalc関数を呼び出します。これは、子プロセスが「ARR」は、親クラスの内部で、なぜそれが私にこのエラーを与えている。この場合、配列には、データを継承する場合子プロセスは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'ではなく)を使用してください。さもなければ、stdoutは正しくフラッシュされません。フォークを説明すると、本全体(またはその中のいくつかの章)が必要になる場合があります。 –
'fork'はC++のスコープ規則を魔法のように変更しません。 – melpomene
おそらく、 'pid_t pid;'の上にある 'int arr [] = ...'を動かすと助けになるでしょうか? –