2013-05-07 38 views
-1

我有一個用叉子潛水的過程。我需要爲每個進程的計算結果創建一個內存區域(矩陣)。我怎樣才能做到這一點?我試過的或我可以使用的所有東西,但它不在進程之間共享,或者我無法使用(不確定是否共享)。有人知道我可以使用什麼?它可以是簡單的,沒有任何安全性。越簡單越好。 我試過shmget但它沒有共享,我不知道如何使用mmap來正確分配或使用它。我嘗試了其他陌生的東西,但沒有。有小費嗎?如何製作共享內存進程(c,linux)?

一些嘗試:

segment_id = shmget(IPC_PRIVATE, (sizeof(int) * linhas_mat1 * colunas_mat2) , S_IRUSR|S_IWUSR); 
matriz_result = (int **) shmat(segment_id, NULL, 0); 

福克斯。每個進程通常可以使用matriz_result作爲矩陣,但內存不共享。每個人都有一個像局部變量。

segment_id = shm_open("/myregion", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); 
matriz_result = mmap(NULL, (sizeof(int) * linhas_mat1 * colunas_mat2), PROT_READ | PROT_WRITE, MAP_SHARED, segment_id, 0); 

用mmap試過這個,但我不知道它是否正確。我對這樣的低級編程不太好,而且我也找不到正確使用它的好例子。

聲明:

int segment_id is; 
int **matriz_result; 
+0

請舉例說明你已經嘗試了什麼,以及爲什麼它沒有工作,然後我們可以幫助你更好。 – Mike 2013-05-07 14:50:39

+0

mmap是要走的路。重新閱讀聯合國教科文組織,谷歌教程,或具體問題。我們無法猜測你做錯了什麼。 – 2013-05-07 14:54:49

+0

另外'mmap'使用'shmopen',而不是'shmget'。那麼一切都應該在手冊頁上。 – 2013-05-07 15:14:13

回答

2
int createMemShare(){ 
    //File descriptor declaration: 
    int fd; 
    //We want to open the file with readwrite,create it, and empty it if it exists 
    //We want the user to have permission to read and write from it 
    fd = open(MEMSHARENAME, O_RDWR| O_CREAT | O_TRUNC, S_IRUSR| S_IWUSR); 
    if(fd <= 0){ 
     puts("Failed in creating memory share ."); 
     return -1; 
    } 
    //Move the file pointer and write an empty byte, this forces the file to 
    //be of the size we want it to be. 
    if (lseek(fd, MEMSHARESIZE - 1, SEEK_SET) == -1) { 
     puts("Failed to expand the memory share to the correct size."); 
    return -1; 
    } 
    //Write out 1 byte as said in previous comment 
    write(fd, "", 1); 

    //Memory share is now set to use, send it back. 
    return fd; 
} 

//Later on... 
int memShareFD = mmap(NULL, MEMSHARESIZE, PROT_READ, MAP_SHARED, fd, 0); 

//And to sync up data between the processes using it: 
//The 0 will invalidate all memory so everything will be checked 
msync(memshareFD,0,MS_SYNC|MS_INVALIDATE); 

你可以試試上面的函數來創建一個共享的內存空間。基本上所有你需要做的就是把它當作任何其他文件來對待。該名男子頁上的代碼示例是相當完整,值得一看爲:check it out here

編輯: 你可能會更好使用shm_openJens Gustedt的意見建議。它比使用我上面寫的函數自己創建文件更簡單,更簡單。

+0

用'shm_open'和你的函數試過。依然沒有。它在嘗試寫入空間的第一刻就會出現分段錯誤。我需要調用一些函數來寫它? – 2013-05-07 16:08:03

+0

只是爲了澄清,你想創建一個矩陣,然後讓每個進程在一些計算過程中使用這個矩陣? – EdgeCaseBerg 2013-05-09 04:36:27

+0

另外,你爲什麼使用fork而不是使用線程?有一個程序可以執行計算並將結果存儲在某個並行的聲音中,就像使用線程的好地方。 – EdgeCaseBerg 2013-05-09 05:49:19