System V共享内存实现进程间通信
#ifndef __11_SHM_HPP__
#define __11_SHM_HPP__
#include<iostream>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
using namespace std;
const char *pathname = "./";
const int PROJ_ID = 0x6664;
inline int error(const char *errstr)
{
printf("%s\n", errstr);
return -1;
}
class sharememory
{
private:
key_t key;
int shmid;
int shm_size;
char *shm_addr;
int shm_destroy();
public:
sharememory(int shmflg, int _shm_size = 1024);
~sharememory();
char *read_shm();
void write_shm(const char *msg);
};
sharememory::sharememory(int shmflg, int _shm_size):shm_size(_shm_size)
{
if ((key = ftok(pathname, PROJ_ID)) < 0)
error("ftok");
if ((shmid = shmget(key, shm_size, shmflg)) < 0)
error("shmget");
shm_addr = (char *)(shmat(shmid, NULL, 0));
}
sharememory::~sharememory()
{
shmdt(shm_addr);
shm_destroy();
}
char *sharememory::read_shm()
{
return shm_addr;
}
void sharememory::write_shm(const char *msg)
{
strcpy(shm_addr, msg);
}
int sharememory::shm_destroy()
{
if (shmctl(shmid, IPC_RMID, NULL) < 0)
error("shmctl");
return 0;
}
#endif
server.cpp
#include "11-shm.hpp"
int main(int argc, char *argv[])
{
sharememory server(IPC_CREAT | IPC_EXCL | 0666, 1024);
while (true)
{
char *buf = new char[1024];
cin >> buf;
server.write_shm(buf);
sleep(1);
if (buf[0] == '$')
break;
}
cout << "exit..." << endl;
server.~sharememory();
return 0;
}
client.cpp
#include "11-shm.hpp"
int main(int argc, char *argv[])
{
sharememory client(IPC_CREAT, 1024);
char *msg = new char[1024];
while (true)
{
msg = client.read_shm();
if (msg == NULL)
exit;
cout << msg << endl;
sleep(1);
}
client.~sharememory();
delete[] msg;
return 0;
}
|