Windows程序通訊 共享記憶體(二)

2021-09-18 06:20:44 字數 1960 閱讀 9853

一、問題:

1.往共享記憶體寫資料時,並不確認共享記憶體裡面的資料是否已經被處理過了

2.傳送資料大小大於共享記憶體大小時,會存在資料丟失問題

二、實現方式:

1.增加乙個讀事件,如果共享記憶體裡面的資料被消費調了,則傳送該事件

2.增加傳送資料的長度,當讀取到的總資料長度等於傳送的長度時,呼叫資料處理函式

三、**

sharememory.h

#ifndef sharememory_h

#define sharememory_h

#include #include #include #include #include "windows.h"

class sharememory

;#endif

sharememory.cpp

#include "stdafx.h"

#include "sharememory.h"

#include sharememory::sharememory(std::wstring strkey, unsigned int nsize) : m_nbuffersize(nsize)

if (m_hmapfile)

else

memset(m_buffer, 0, m_nbuffersize);

m_ptrreadthread = std::make_shared(std::bind(&sharememory::readdata, this));

} }}sharememory::~sharememory()

if (m_hmapfile)

if (m_writeevent)

if (m_readevent) }

void sharememory::registereceiver(std::functionpfunreceiver)

void sharememory::writedata(char *data, unsigned int nlength)

unsigned char *senddata = (unsigned char *)malloc(4 + nlength);

if (!senddata)

char lenhead[4] = ;

int2bytes(nlength, 4, senddata);

memcpy(senddata + 4, data, nlength);

nlength += 4;

int nalreadysendsize = 0;

while (nlength > 0)

} }

//釋放記憶體

delete senddata;

senddata = nullptr;

}void sharememory::readdata()

unsigned int nreveicelen = 0;

unsigned int nsendlen = 0;

unsigned char *databegin = nullptr;

while (m_bthreadrunning)

else

if (nreveicelen >= nsendlen)

resetevent(m_writeevent);

setevent(m_readevent);

}break;

} default:

std::cout<<"wait error :" << getlasterror()<> 8 * (3 - i) & 0xff); }}

int sharememory::bytes2int(unsigned char* pdata, int nlength)

int nvalue = 0;

for (int i = 0; i < nlength; i++)

return nvalue;

}

程序通訊 共享記憶體

定義 共享記憶體,就是通過核心操作,在記憶體上開闢一塊供多個程序共同訪問的記憶體塊。這塊記憶體塊的建立和 銷毀是由核心來控制 當然,也可以在程序內部呼叫系統庫函式來建立和銷毀,類似於訊息機制和訊號 量機制 在這個記憶體塊上,程序可以像操作記憶體一樣操作共享區記憶體。作用 第乙個,就是提供程序間大資訊...

程序通訊共享記憶體

共享記憶體是允許多個程序共享記憶體 共享記憶體結構 struct shmid ds struc ipc permshm perm 指向該記憶體指標 int shm segsz 共享記憶體的大小 ushort shm lkcnt 共享記憶體被鎖定的時間 pid t shm cpid 最近呼叫shomp...

程序間通訊 共享記憶體

下面是自己寫的乙個簡單的共享記憶體的程序間通訊的例子。共享記憶體是用於程序間大量資料共享的一種方法。include include include include include include int main if buf1 shmat shmid,0,0 void 1 strcpy buf1,...