Linux shared Memory的写入与读取
来源:互联网 发布:access数据库教程网盘 编辑:程序博客网 时间:2024/06/05 13:31
作用
多个进程就可以访问相同的物理存储,以此实现多进程通信。
特点
提供了进程间共享数据的最快途径
不在读写数据之间提供任何同步方法
常用的函数
shmget函数用于创建/打开一个共享存储段
int shmget(key_t key, size_t size, int shmflg);
调用shmat函数来连接这个共享段到自己的地址空间
void *shmat(int shmid, void *shmaddr, int shmflg);
使用shmdt函数将它从进程地址空间分离
int shmdt(void *shmaddr);
写入与读取操作:
服务程序和客户程序共享一个存储段,服务程序创建共享存储段并写入信息等待回馈,客户程序接收信息并重写共享存储段并分离,服务程序接收客户发的信息并退出。
server.c
#include<sys/shm.h>#include<stdio.h>#include<stdlib.h>void main(){char c[18] = "Hello, I am server";int shmid;key_t key = 56789;char *shm, *s;shmid = shmget(key, 20, IPC_CREAT|0666);//创建并赋权限(所有用户都可读写)if( shmid == -1){printf("Error: create shared Memory");exit(0);}shm = shmat(shmid, NULL, 0);if( shm == -1){printf("Error: connect shared Memory");exit(0);}s = shm;for(int i=0; i<18; i++){*s = c[i];s++;}*s = NULL;while(*shm != '*'){printf("Waiting...\nThe shared Memory is :");for(s = shm; *s != NULL; s++){if(*s =='*'){putchar('\n');exit(0);}putchar( *s );}sleep(1);putchar('\n');}}client.c
#include<sys/shm.h>#include<stdio.h>#include<stdlib.h>void main(){int shmid;char c[15] = "Hi, I am client";key_t key = 56789;char *shm, *s;shmid = shmget(key, 0, 0666);if( shmid == -1){printf("Error: create shared Memory");exit(0);}shm = shmat(shmid, NULL, 0);if( shm == -1){printf("Error: connect shared Memory");exit(0);}for(s = shm; *s != NULL; s++){putchar( *s );}putchar('\n');for(int i=0; i<16; i++){if( i == 15){*shm = '*';}else{*shm = c[i];shm++;}}shmdt( shm );//分离共享存储段exit(0);}运行步骤:
gcc server.c -o server
gcc client.c -o client
./server
重开一个命令行
./client
阅读全文
0 0
- Linux shared Memory的写入与读取
- Linux Shared Memory的查看与设置
- Linux IPC - Shared memory
- Linux shared memory
- postgresql的shared memory
- Linux Kernel Shared Memory 剖析
- Linux Kernel Shared Memory 剖析
- Linux Kernel Shared Memory 剖析
- Cookie 的写入与读取
- Cookie 的写入与读取
- Cookie 的写入与读取
- cookie的写入与读取
- word的读取与写入
- BMP 的读取与写入
- 文件的读取与写入
- RandomAccessFile的读取与写入
- JSON的读取与写入
- Linux系统编程:文件的读取写入
- JavaScript
- PHP中数组及相关函数(一)
- 观察者模式
- 管理fragment
- jQueryhtml操作和css操作
- Linux shared Memory的写入与读取
- vi 常用命令行 撤销 删除行 复制 等等
- 多种退出vim的方法
- Android 琐碎小知识(一)
- linux下C++程序调试工具GDB
- 基于JDBC的增删改查
- 什么是ORM?
- Web.xml中设置Servlet和Filter时的url-pattern匹配规则
- struts2结果处理方式(结果跳转方式)