2017-10-08 7 views
-2

나는 fork()를 사용하여 자식 프로세스를 만들고있다. 자식 프로세스는 부모 프로세스의 데이터를 상속하므로 부모 프로세스에 배열을 만들고 배열 내에서 홀수 인덱스를 가진 모든 요소의 합계를 계산하는 자식 프로세스 내에서 calc 함수를 호출합니다. 그것은 자식 프로세스는 '도착'는 부모 클래스의 내부에, 왜 다음 날이 오류를주고있다이 경우, 배열에 데이터를 상속하는 경우하위 프로세스가 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 
+0

http://advancedlinuxprogramming.com/ 읽기; 위의 프로그램에서'exit' ('_exit'가 아님)을 사용하십시오. 그렇지 않으면 stdout이 제대로 플러시되지 않습니다. 'fork '를 설명하면 전체 책 (또는 여러 장)이 필요할 수 있습니다. –

+3

'fork'는 마술처럼 C++의 스코핑 규칙을 변경하지 않습니다. – melpomene

+0

아마도''int arr [] = ...''pid_t pid; '위로 움직이는 것이 도움이 될까요? –

답변

2

컴파일러에 관한 한, fork은 정상적인 기능입니다. 코드의이 시점에서

int sum = calc(arr); 

는 범위가 더 arr 변수가없는, 그래서 당신은 오류가 발생합니다.

다른 방식으로 보면 fork은 실행중인 프로세스의 복사본을 만듭니다. fork 지점에는 부모 프로세스에 arr 배열이 없으므로 하위 프로세스에도 배열이 없습니다. arrfork 후, 나중에 생성됩니다

// 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를 호출하기 전에 작성해야합니다.

+0

각 프로세스에는 자체 가상 주소 공간이 있습니다. 따라서 변수는 둘 다 "동일"하지 않습니다. –

+0

@BasileStarynkevitch 네, 저는 그것이 실행중인 프로세스의 복사본이라고 말했습니다. – melpomene