使用mmap可以方便地添加共享内存
使用mmap添加的共享内存。
局限:
只能在有亲属关系的进程之间使用。
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/mman.h> #include <string.h> #include <wait.h> //#include <sys/types.h> //#include <sys/stat.h> //#include <fcntl.h> #define MEMSIZE 1024 int main() { char *str; pid_t pid; str = (char *)mmap(NULL, MEMSIZE, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0); if (str == MAP_FAILED) { perror("mmap"); exit(1); } pid = fork(); if (pid < 0) { perror("fork"); exit(1); } if (pid == 0) { strncpy(str, "Hello!", 6); munmap(str, MEMSIZE); printf("child exit\n"); exit(0); } else { wait(NULL); puts(str); munmap(str, MEMSIZE); printf("father exit\n"); exit(0); } }
运行结果:
[work@ mmap1]$g++ -o mmap_sharedm mmap_sharedm.cpp [work@ mmap1]$./mmap_sharedm child exit Hello! father exit
注意以上各个头文件的作用:
//#include <stdio.h> mmap_sharedm.cpp:22: error: `perror' was not declared in this scope mmap_sharedm.cpp:28: error: `perror' was not declared in this scope mmap_sharedm.cpp:35: error: `printf' was not declared in this scope mmap_sharedm.cpp:40: error: `puts' was not declared in this scope mmap_sharedm.cpp:42: error: `printf' was not declared in this scope //#include <stdlib.h> mmap_sharedm.cpp:23: error: `exit' was not declared in this scope mmap_sharedm.cpp:29: error: `exit' was not declared in this scope mmap_sharedm.cpp:36: error: `exit' was not declared in this scope mmap_sharedm.cpp:43: error: `exit' was not declared in this scope //#include <unistd.h> mmap_sharedm.cpp:26: error: `fork' was not declared in this scope //#include <sys/mman.h> mmap_sharedm.cpp:18: error: `PROT_READ' was not declared in this scope mmap_sharedm.cpp:18: error: `PROT_WRITE' was not declared in this scope mmap_sharedm.cpp:18: error: `MAP_SHARED' was not declared in this scope mmap_sharedm.cpp:18: error: `MAP_ANONYMOUS' was not declared in this scope mmap_sharedm.cpp:19: error: `mmap' was not declared in this scope mmap_sharedm.cpp:21: error: `MAP_FAILED' was not declared in this scope mmap_sharedm.cpp:34: error: `munmap' was not declared in this scope mmap_sharedm.cpp:41: error: `munmap' was not declared in this scope //#include <string.h> mmap_sharedm.cpp:33: error: `strncpy' was not declared in this scope //#include <wait.h> mmap_sharedm.cpp:39: error: no matching function for call to `wait::wait(NULL)' /usr/include/bits/waitstatus.h:68: note: candidates are: wait::wait() /usr/include/bits/waitstatus.h:68: note: wait::wait(const wait&)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!