Linux下内存共享的一个实例(设置共享内存,一个程序写,一个程序读)
来源:互联网 发布:淘宝咋评价 编辑:程序博客网 时间:2024/05/16 12:34
首先先使用shmget建立一块共享内存,然后向该内存中写入数据并返回该共享内存shmid
使用另一个程序通过上一程序返回的shmid读该共享内存内的数据
建立共享内存并写入数据的程序
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <errno.h>
void get_buf(char *buf)
{
int i=0;
while((buf[i]=getchar())!='\n'&&i<1024)
i++;
{
int shmid;
shmid=shmget(IPC_PRIVATE,sizeof(char)*1024,IPC_CREAT|0666);
if(shmid==-1)
{
perror("shmget");
}
char *buf;
if((int)(buf=shmat(shmid,NULL,0))==-1)
{
perror("shmat");
exit(1);
}
get_buf(buf);
printf("%d\n",shmid);
return 0;
}
读取数据的程序
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
int shmid;
shmid=atoi(argv[1]);
char *buf;
if((int)(buf=shmat(shmid,NULL,0))==-1)
{
perror("shmat");
exit(1);
}
printf("%s\n",buf);
shmdt(buf);
return 0;
}
命令行的第一个参数设为第一个程序输出的数字
如
使用完以后可以使用
ipcrm -m 19562507
来删除该共享内存
使用另一个程序通过上一程序返回的shmid读该共享内存内的数据
建立共享内存并写入数据的程序
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <errno.h>
void get_buf(char *buf)
{
int i=0;
while((buf[i]=getchar())!='\n'&&i<1024)
i++;
}
{
int shmid;
shmid=shmget(IPC_PRIVATE,sizeof(char)*1024,IPC_CREAT|0666);
if(shmid==-1)
{
perror("shmget");
}
char *buf;
if((int)(buf=shmat(shmid,NULL,0))==-1)
{
perror("shmat");
exit(1);
}
get_buf(buf);
printf("%d\n",shmid);
return 0;
}
读取数据的程序
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
int shmid;
shmid=atoi(argv[1]);
char *buf;
if((int)(buf=shmat(shmid,NULL,0))==-1)
{
perror("shmat");
exit(1);
}
printf("%s\n",buf);
shmdt(buf);
return 0;
}
命令行的第一个参数设为第一个程序输出的数字
如
使用完以后可以使用
ipcrm -m 19562507
来删除该共享内存
http://blog.163.com/lixiangqiu_9202/blog/static/53575037201291014947937/
0 0
- Linux下内存共享的一个实例(设置共享内存,一个程序写,一个程序读)
- Linux 创建共享内存 从一个程序写一个程序读
- [代码实例]一个共享内存的class
- Erlang 程序引发共享内存 bug 的一个例子
- linux两个程序通过共享内存通信的一个简单例子
- linux两个程序通过共享内存通信的一个简单例子
- 如何写一个内存溢出的程序
- Linux下共享内存简单程序示例
- linux/Unix 共享内存 mmap() 函数使用的一个问题
- 一个共享内存封装类的源码
- linux共享内存的使用--测试程序
- 进程地址空间的共享(可以实现一个程序只有一个实例运行)
- 写一个能装载硬盘数据到内存的MBR程序
- 如何写一个爆掉内存的PHP程序
- UNIX 如果查询一个共享内存已经被IPCRM,程序中如何操作保证安全
- 共享内存测试程序
- 共享内存--程序
- 关于linux共享内存中的一个重要函数shmget
- hdu 5017 Ellipsoid(模拟退火)
- 设计模式笔记-享元模式
- 如何在Ubuntu下搭建tftp服务器(最简单的安装配置)
- 生物识别简介(Biometric)
- java大整数的用法
- Linux下内存共享的一个实例(设置共享内存,一个程序写,一个程序读)
- “破网”利器一箩筐——移动互联网分析工具推荐
- struts中Action的线程安全性分析
- leetcode - Pascal's Triangle
- 新手练习之~unity3d射击类游戏~
- 蓝的成长记——追逐DBA(6): 做事与做人:小技术,大为人
- 一步一步学Linux C:共享内存通信实例
- 双向队列(STL做法)
- 关于代码优化中inline函数的使用