shm_test_server.cpp

来自「股票分析源代码」· C++ 代码 · 共 109 行

CPP
109
字号
#include <string>

#include "ace/MMAP_Memory_Pool.h"
#include "ace/Shared_Memory_Pool.h"
#include <ace/Null_Mutex.h>
#include "ace/Malloc.h"
#include "ace/Malloc_T.h"

using namespace std;

#define DATA_SIZE 100
#define MESSAGE1 "Hiya over there client process shm msg 1"
#define MESSAGE2 "Did you hear me the first time? shm msg2"

struct ShmData
{
	//std::string name;
	char name[256];
	int num;	
};

char* poolname="My_Pool";

#ifdef _WIN32_
typedef ACE_Malloc<ACE_MMAP_Memory_Pool,ACE_Null_Mutex> Malloc_Allocator;
#else
typedef ACE_Malloc<ACE_Shared_Memory_Pool,ACE_Null_Mutex> Malloc_Allocator;
#endif

static void server (void)
{
	//Create the memory allocator passing it the shared memory
	//pool that you want to use
	Malloc_Allocator shm_allocator(poolname);

	//Create a message, allocate memory for it and bind it with
	//a name so that the client can the find it in the memory
	//pool

	char* Message1=(char*)shm_allocator.malloc(strlen(MESSAGE1));
	ACE_OS::strcpy(Message1,MESSAGE1);
	shm_allocator.bind("FirstMessage",Message1);
	ACE_DEBUG((LM_DEBUG,"<<%s\n",Message1));

	//How about a second message
	char* Message2=(char*)shm_allocator.malloc(strlen(MESSAGE2));
	ACE_OS::strcpy(Message2,MESSAGE2);
	shm_allocator.bind("SecondMessage",Message2);
	ACE_DEBUG((LM_DEBUG,"<<%s\n",Message2));
	
	ShmData data;
	//data.name = "hello world";
	strcpy(data.name,"hello world");
	data.num = 5;

	ShmData* p_data;
	
	p_data = new ShmData;
	memset(p_data,'\0',sizeof(ShmData));
	strcpy(p_data->name,"hello world 4");
	p_data->num = 4;
	
	ShmData* p_data1;
	
	p_data1 = new ShmData;
	memset(p_data1,'\0',sizeof(ShmData));
	strcpy(p_data1->name,"hello world 4");
	p_data1->num = 4;
	
	char* Message3=(char*)shm_allocator.malloc(sizeof(ShmData));
	//ACE_OS::memcpy(Message3,p_data,sizeof(ShmData));
	p_data = (ShmData*)Message3;
	//memset(p_data,'\0',sizeof(ShmData));
	strcpy(p_data->name,"hello world 6");
	p_data->num = 6;
	shm_allocator.bind("ThreeMessage",(void*)Message3);
	strcpy(p_data->name,"hello world 7");
	p_data->num = 7;
	//shm_allocator.bind("ThreeMessage",(void*)&data);
	
	/*
	char* Message4=(char*)shm_allocator.malloc(sizeof(ShmData*));
	ACE_OS::memcpy(Message4,&p_data1,sizeof(ShmData*));	
	shm_allocator.bind("FourMessage",(void*)Message4);
	*/
	
	//Set the Server to go to sleep for a while so that the client has
	//a chance to do its stuff
	ACE_DEBUG((LM_DEBUG,
		"Server done writing.. going to sleep zzz..\n\n\n"));
	ACE_OS::sleep(10);

	delete p_data;
	
	//Get rid of all resources allocated by the server. In other
	//words get rid of the shared memory pool that had been
	//previously allocated
	shm_allocator.remove();
}


int main (int, char *[])
{
	server ();

	return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?