2017-10-08 144 views
-2

我使用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 
+0

閱讀http://advancedlinuxprogramming.com/;在上面的程序中,使用'exit'(而不是'_exit'),否則標準輸出將不會正確刷新。解釋'fork'可能需要整本書(或其中的幾章)。 –

+3

'fork'不會奇蹟般地改變C++的範圍規則。 – melpomene

+0

也許移動'int arr [] = ...'在pid_t pid之上''可能有幫助嗎? –

回答

2

就編譯器而言,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之前創建它。

+0

每個進程都有自己的虛擬地址空間。所以這兩個變量不是「相同的」。 –

+0

@BasileStarynkevitch是的,我說這是一個運行過程的副本。 – melpomene