共享内存

本文介绍了如何使用C++进行共享内存的读写操作。通过示例代码`wshm.cc`和`rshm.cc`,展示了如何创建、链接共享内存,并进行数据的更新和读取。这两个程序分别用于写入和读取指定位置的数据,实现了进程间的直接通信。
摘要由CSDN通过智能技术生成
共享内存:最快的IPC对象,不借助第三方,可被多个进程直接访问
写共享内存wshm.cc
#include <iostream>
#include <sys/shm.h>
using namespace std;


#define VERIFY(a,b)\
if(a)\
{\
cout<<b<<"  fail"<<endl;\
exit(-1);\
}\
else\
cout<<b<<" success"<<endl;\


int main(int argc, char* argv[])
{
int shmid;
int no;
char* pmat=NULL;
char buf[1024]={};


VERIFY((shmid=shmget(0x1234, 10*1024, IPC_CREAT|0777))<0, "open shm");


VERIFY((pmat=(char*)shmat(shmid, NULL, 0))<0, "shmat");


cout<<"input the no you want to update:";
cin>>no;
cout<<"input your data:";
cin>>buf;

memcpy(pmat+no*1024, buf, 1024);
VERIFY(shmdt(pmat));
}


读共享内存rshm.cc
#include <iostream>
#include <sys/shm.h>
using namespace std;


#define VERIFY(a,b)\
if(a)\
{\
cout<<b<<" fail"<<endl;\
exit(-1);
}\
else\
cout<<b<<" success";


int main(int argc, char*argv[])
{
int shmid;
int no;
char* pmat = NULL;
char buf[1024]={};


VERIFY((shmid=shmget(0x1234, 10*1024, IPC_CREAT|0777))<0, "open shm");


VERIFY((pmat=(char*)shmat(shmid, NULL, 0))<0, "link shm");


cout<<"input the no you want to read:";
cin>>no;
memcpy(buf, pmat+no*1024, 1024);


cout<<buf<<endl;


shmdt(pmat);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值