【发布时间】:2012-07-29 03:16:33
【问题描述】:
当我这样做时:
myProgram.h
myProgram.c
struct PipeShm
{
// all my fields
// more
// ...
};
struct PipeShm myPipe = { /* initialization for all fields */ };
struct PipeShm * sharedPipe = &myPipe;
void func()
{
sharedPipe = mmap (NULL, sizeof * sharedPipe, PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS, -1, 0);
}
当我mmap 指针sharedPipe 时,如果我从main() 调用myProgram 代码中的任何方法,所有进程是否会共享我与myPipe 结构共享的确切共享内存?
或者每个新创建的孩子都会有一个自己的新myPipe?
问候
编辑:
这是在我阅读了 cmets 和答案之后:现在进行了更改,并且仅在分配段后才初始化段的值:
#include "my_pipe.h"
struct PipeShm * sharedPipe = NULL;
int shm_pipe_init()
{
if (!sharedPipe)
{
int myFd = shm_open ("/myregion", O_CREAT | O_TRUNC | O_RDWR, 0600);
if (myFd == -1)
error_out ("shm_open");
// Allocate some memory in the region - We use ftruncate, write(2) would work just as well
int retAlloc = ftruncate (myFd, sizeof * sharedPipe);
if (retAlloc < 0)
error_out("ftruncate");
sharedPipe = mmap (NULL, sizeof * sharedPipe,
PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS, myFd, 0);
if (!sem_init (&sharedPipe->semaphore, 1, 0))
{
sharedPipe->init = TRUE;
sharedPipe->flag = FALSE;
sharedPipe->ptr1 = NULL;
sharedPipe->ptr2 = NULL;
sharedPipe->status1 = -10;
sharedPipe->status2 = -10;
sharedPipe->semaphoreFlag = FALSE;
sharedPipe->currentPipeIndex = 0;
}
else
perror ("shm_pipe_init");
}
return 1; // always successful
}
但问题仍然存在,共享内存似乎在进程之间并没有如此共享,因为在运行和分叉该 main 时:
int main()
{
int spd, pid, rb;
char buff[4096];
fork();
shm_pipe_init();
// more
return 0;
}
我仍然得到输出,模拟只有一个进程正在运行的行为(而不是多个输出,我只得到一个 one 或 couple ,取决于进程之间的竞争条件)。
【问题讨论】:
-
“所有进程”是什么意思?系统中的所有进程,还是原来的所有子进程等等?
-
@tbert: 所有进程 - 表示子进程、孙子进程...等
-
书写提示:英文标点(逗号、冒号、分号、句号、问号等)前没有空格。
标签: c linux operating-system shared-memory mmap