标签:blog io os for div sp log on c
#include <iostream>
#include <sys/shm.h>
using namespace std;
class Test
{
private:
int status;
public:
Test():status(0){}
Test(const int& s):status(s){}
void init(){status = 0;}
int getStatus(){ return status; }
void setStatus(const int& s){ status = s; }
};
int main()
{
key_t key;
int shmid;
key = ftok("/home/yu/shm/ipc",‘R‘);
shmid = shmget(key,1024,IPC_CREAT|0604);
int p = fork();
if(p>0)
{
sleep(2);
cout<<"father wake up"<<endl;
Test *t = (Test*)shmat(shmid,0,0);
cout<<t->getStatus()<<endl;
shmdt((void*)t);
}else
{
Test *t = (Test*)shmat(shmid,0,0);
t->init();
t->setStatus(200);
cout<<"child set"<<endl;
}
}
这个例子可以直观的看到如何将一个对象放进共享内存,就是把共享内存所指向的那一段空间转成我们的对象所存放的结构,然后就可以操作了。
标签:blog io os for div sp log on c
原文地址:http://www.cnblogs.com/dy-techblog/p/3977086.html