建立程序間共享記憶體對映

2021-06-16 16:20:50 字數 1991 閱讀 6741

1、首先建立乙個互斥體物件。

#define share_mutex _t("your mutex name")

handle hsharemuex = openmutex(mutex_all_access,false,share_mutex);

if(hsharemuex==null)

; }

2、建立共享記憶體

#define share_mapfile _t("your mapfile name")

if (hmapfile == null)

之後呼叫下面的函式進行讀寫該記憶體

3、讀寫共享記憶體的函式

struct sharememory

//獲取共享記憶體資料並鎖定

static bool getsharememory_lock(out handle& hhandle,sharememory* psf=null)

dword dwret=waitforsingleobject(hmutex,infinite);

if(dwret!=wait_object_0)

hhandle=hmutex;

if(hmap==null)

void* pfile = mapviewoffile(hmap, file_map_write | file_map_read, 0, 0, 0);

if (pfile == null)

if(psf!=null)

*psf = *(sharememory*)pfile;

unmapviewoffile(pfile);

closehandle(hmap);

// releasemutex(hmutex);

// closehandle(hmutex);

return true;

}//寫入共享記憶體資料並解鎖

static bool setsharememory_unlock(in handle hhandle,sharememory* psf=null)

void* pfile = mapviewoffile(hmap, file_map_write | file_map_read, 0, 0, 0);

if (pfile == null)

if(psf!=null)

*(sharememory*)pfile = *psf;

bool s=flushviewoffile(pfile,sizeof(sharememory));

// sharememory temp;

// temp=*(sharememory*)mapviewoffile(hmap, file_map_write | file_map_read, 0, 0, 0);

unmapviewoffile(pfile);

closehandle(hmap);

releasemutex(hmutex);

closehandle(hmutex);

return true;

}static bool getsharememory(sharememory& sf)

dword dwret=waitforsingleobject(hmutex,infinite);

if(dwret!=wait_object_0)

if(hmap==null)

void* pfile = mapviewoffile(hmap, file_map_write | file_map_read, 0, 0, 0);

if (pfile == null)

sf = *(sharememory*)pfile;

unmapviewoffile(pfile);

closehandle(hmap);

releasemutex(hmutex);

closehandle(hmutex);

return true;

}

程序間共享記憶體

位於系統的交換分割槽 include incude int shmget key t key,size t size,int shm ipc excl ipc creat一起使用可確保共享記憶體已存在時返回錯誤 void shmat int shm id,const void shm addr,in...

程序間通訊 共享記憶體

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

linux 程序間共享記憶體

可以採用sysv的shmget shmat 實現。但是我更喜歡shm open mmap 更簡單。writer.c include include include include include include include include struct ofs stat int main voi...