【问题标题】:How to share memory between two child processes belonging to the same parent如何在属于同一个父进程的两个子进程之间共享内存
【发布时间】:2019-03-03 17:00:38
【问题描述】:

我有两个使用exec() 系统调用启动的子进程(都具有相同的父进程),我希望这两个进程通过mmap() 映射到IPC 的同一个文件。我遇到的问题是一个进程使用mmap() 返回的指针写入数据(它是自己的pid),但另一个进程无法读取该数据。此外,我希望第二个子进程使用该 pid 来了解第一个子进程的状态。任何帮助将不胜感激,因为我对此很陌生。

父进程:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
int main(int argc, char **argv)
{ 
pid_t process, f_child, s_child;
int status;
sem_t synch; 
sem_init(&synch, 1, 0);
process = fork();
if(process<0)
{
perror("Fork Failed");
exit(1);
}
if(process>)
{
//Parent!!
sem_post(&synch); // signaling to child
f_child = wait(&status);
s_child = fork();
if(s_child==0)
{
//Second Child Process!!
execlp("./secondChild", "./secondChild", NULL);
}
}
else
{
//First Child Process!!
sem_wait(&synch);
execlp("./firstChild","./firstChild", NULL);
}
 return 0;
}

第一个子进程:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
int fd = shm_open("./myFile", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
int *sharedMem = mmap(0, 256, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, fd, 0);


*sharedMem = getpid();
printf("Child Process 1 wrote message : %d", *sharedMem);
exit(10);
return 0;
}

第二个子进程:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
int fd = shm_open("./myFile", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
int *sharedMem = mmap(0, 256, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, fd, 0);


printf("Child Process 2 readmessage : %d", *sharedMem);
return 0;
}

【问题讨论】:

  • 我建议您首先向您的“子”进程添加一些错误检查。他们的shm_open 电话真的成功了吗? mmap 电话怎么样?
  • @Someprogrammerdude 我对shm_open()mmap() 调用都进行了错误检查。还是不行。。

标签: c linux fork exec mmap


【解决方案1】:

如果你 man sem_init on linux ( 至少在我的 ) 它说 sem_t 必须在共享内存位置;父进程的栈不是共享内存区域。该手册在这方面有点模棱两可,因为它继续说分叉的孩子继承了这些映射,但我很确定这意味着分叉的孩子继承了共享的映射。

【讨论】:

    【解决方案2】:

    MAP_ANONYMOUS 请求匿名内存,即不独立于任何文件的内存,并且忽略 mmap 的 fd 参数。删除它。

    【讨论】:

      猜你喜欢
      • 2013-07-16
      • 1970-01-01
      • 2010-11-15
      • 2018-07-06
      • 2014-09-02
      • 1970-01-01
      • 2015-03-17
      • 2019-04-02
      • 2011-11-06
      相关资源
      最近更新 更多