栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

有两种方法:

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

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: %sn", shmem);    memcpy(shmem, child_message, sizeof(child_message));    printf("Child wrote: %sn", shmem);  } else {    printf("Parent read: %sn", shmem);    sleep(1);    printf("After 1s, parent read: %sn", shmem);  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/399068.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号