共享内存:最快的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);
}
写共享内存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);
}