共享内存通过直接访问同一物理内存实现高效IPC。示例中writer.c创建并写入数据,reader.c读取数据,需注意同步、键值生成、资源清理和权限设置。

共享内存是Linux进程间通信(IPC)中效率最高的一种方式,因为它允许两个或多个进程直接访问同一块物理内存区域,避免了数据在内核与用户空间之间的多次拷贝。下面通过一个完整的示例,展示如何使用System V共享内存实现两个进程间的通信。
使用System V共享内存通信通常包括以下步骤:
该程序创建共享内存,写入数据,并等待读取完成。
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define SHM_SIZE 1024 // 共享内存大小
int main() {
key_t key = ftok("shmfile", 65); // 生成键值
int shmid = shmget(key, SHM_SIZE, 0666 | IPC_CREAT); // 创建共享内存
char *shmaddr = (char*)shmat(shmid, NULL, 0); // 映射到进程地址空间
printf("共享内存已创建,开始写入数据...\n");
const char *msg = "Hello from writer process!";
strcpy(shmaddr, msg);
printf("数据已写入: %s\n", shmaddr);
printf("等待读取进程完成...(按回车键继续)\n");
getchar();
// 分离并删除共享内存
shmdt(shmaddr);
shmctl(shmid, IPC_RMID, NULL);
printf("共享内存已删除。\n");
return 0;
}
该程序连接到已存在的共享内存,读取数据并分离。
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <unistd.h>
#define SHM_SIZE 1024
int main() {
key_t key = ftok("shmfile", 65);
int shmid = shmget(key, SHM_SIZE, 0666); // 获取已有共享内存
char *shmaddr = (char*)shmat(shmid, NULL, 0);
printf("连接到共享内存,正在读取数据...\n");
printf("接收到的数据: %s\n", shmaddr);
// 分离共享内存
shmdt(shmaddr);
printf("已从共享内存分离。\n");
return 0;
}
将上面两个文件保存为writer.c和reader.c,然后编译:
gcc writer.c -o writer运行顺序:
以上就是Linux如何使用共享内存通信_LinuxIPC共享内存完整示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号