2013-05-07 55 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