SharedMemory.h
#ifndef SHAREDMEMORY_H
#define SHAREDMEMORY_H
namespace Utility
{
//获取shmId
int initShm(const char* fileName);
//清除shmId
int closeShmMessage(int shmId);
//向shmId写数据
int writeShmMessage(int shmId,const void* msg,int msgLen);
//从shmId读数据
void* readShmMessage(int shmId);
}//end of namespace Utility
#endif // SHAREDMEMORY_H
SharedMemory.cpp
#include "SharedMemory.h"
#include <sys/types.h>
#include <sys/shm.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
namespace Utility
{
/*
获取shmId
*/
int initShm(const char* fileName)
{
if(access(fileName,R_OK)!=0)
{
int fd = open(fileName,O_RDWR|O_CREAT|O_APPEND);
close(fd);
}
key_t key = ftok(fileName,0);
if(key==-1){
return -1;
}
return shmget(key,4096,IPC_CREAT);
}
/*
清除shmId
*/
int closeShmMessage(int shmId)
{
return shmctl(shmId,IPC_RMID,0);
}
/*
向shmId写数据
*/
int writeShmMessage(int shmId,const void* msg,int msgLen)
{
void *pmessage = shmat(shmId,NULL,0);
memcpy(pmessage, msg, msgLen);
if(shmdt(pmessage)==-1){
return -1;
}
return 0;
}
/*
从shmId读数据
*/
void* readShmMessage(int shmId)
{
return shmat(shmId,NULL,0);
}
}//end of namespace Utility
testSharedMemory.cpp
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include "SharedMemory.h"
using namespace std;
using namespace Utility;
struct Message
{
int m;
char str[32];
};
static const char* g_file = "testShm";
int main()
{
Message msg1;
msg1.m = 1;
strcpy(msg1.str,"hello");
int shmId = initShm(g_file);
if(shmId<0)
{
cout << "shmget error" << endl;
return -1;
}
pid_t pid;
if((pid=fork())==0)
{
writeShmMessage(shmId,&msg1,sizeof(msg1));
exit(0);
}
if(waitpid(pid,NULL,0)!=pid)
{
cout << "wait error" << endl;
return -1;
}
Message* msg2 = (Message* )readShmMessage(shmId);
cout << msg2->m << "," << msg2->str << endl;
cout << "clear:" << closeShmMessage(shmId) << endl;
return 0;
}
1,hello
clear:0