您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在C语言中的Linux中使用共享内存

如何在C语言中的Linux中使用共享内存

有两种方法shmgetmmap。我将讨论mmap,因为它更现代,更灵活,但是如果您想使用旧式工具,可以看看man shmget或本教程)。

mmap()函数可用于分配具有高度可自定义参数的内存缓冲区,以控制访问和权限,并在必要时通过文件系统存储支持它们。

以下函数创建一个进程中可以与其子进程共享的内存中缓冲区:

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

void* create_shared_memory(size_t size) {
  // Our memory buffer will be readable and writable:
  int protection = PROT_READ | PROT_WRITE;

  // The buffer will be shared (meaning other processes can access it), but
  // anonymous (meaning third-party processes cannot obtain an address for it),
  // so only this process and its children will be able to use it:
  int visibility = MAP_SHARED | MAP_ANONYMOUS;

  // The remaining parameters to `mmap()` are not important for this use case,
  // but the manpage for `mmap` explains their purpose.
  return mmap(NULL, size, protection, visibility, -1, 0);
}

下面是一个示例程序,该程序使用上面定义的功能来分配缓冲区。父进程将编写一条消息,进行分叉,然后等待其子进程修改缓冲区。这两个进程都可以读取和写入共享内存。

#include <string.h>
#include <unistd.h>

int main() {
  char parent_message[] = "hello";  // parent process will write this message
  char child_message[] = "goodbye"; // child process will then write this one

  void* shmem = create_shared_memory(128);

  memcpy(shmem, parent_message, sizeof(parent_message));

  int pid = fork();

  if (pid == 0) {
    printf("Child read: %s\n", shmem);
    memcpy(shmem, child_message, sizeof(child_message));
    printf("Child wrote: %s\n", shmem);

  } else {
    printf("Parent read: %s\n", shmem);
    sleep(1);
    printf("After 1s, parent read: %s\n", shmem);
  }
}
其他 2022/1/1 18:15:50 有639人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶