博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一则简单的Windows共享内存IPC代码
阅读量:4148 次
发布时间:2019-05-25

本文共 2850 字,大约阅读时间需要 9 分钟。

Windows共享内存可以让两个进程对同一块内存进行读写。

以下有2个进程,a.cpp生成A进程,b.cpp生成b进程。那么a进程将不停地读名为"Global\\MyFileMappingObject"的共享内存块,而b进程不停地写名为"Global\\MyFileMappingObject"的共享内存块。从而实现IPC。

//a.cpp#include 
#include
#include
#include
#include
using namespace std;#define BUF_SIZE 256TCHAR szName[]=TEXT("Global\\MyFileMappingObject"); //指向同一块共享内存的名字int main(int argc, char *argv[]){ HANDLE hMapFile; LPCTSTR pBuf; hMapFile = CreateFileMapping( INVALID_HANDLE_VALUE, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) BUF_SIZE, // maximum object size (low-order DWORD) szName); // name of mapping object if (hMapFile == NULL) { _tprintf(TEXT("Could not create file mapping object (%d).\n"), GetLastError()); return 1; } pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, BUF_SIZE); if (pBuf == NULL) { _tprintf(TEXT("Could not map view of file (%d).\n"), GetLastError()); CloseHandle(hMapFile); return 1; } //从main开始至此,A B process代码一样,都是获取名为"Global\\MyFileMappingObject"的共享内存的指针 //以下代码,A不停地读共享内存pBuf while(1) { cout<
<

 

//b.cpp#include 
#include
#include
using namespace std;#define BUF_SIZE 256TCHAR szName[]=TEXT("Global\\MyFileMappingObject"); //指向同一块共享内存的名字int main(){ HANDLE hMapFile; LPCTSTR pBuf; hMapFile = CreateFileMapping( INVALID_HANDLE_VALUE, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) BUF_SIZE, // maximum object size (low-order DWORD) szName); // name of mapping object if (hMapFile == NULL) { _tprintf(TEXT("Could not create file mapping object (%d).\n"), GetLastError()); return 1; } pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, BUF_SIZE); if (pBuf == NULL) { _tprintf(TEXT("Could not map view of file (%d).\n"), GetLastError()); CloseHandle(hMapFile); return 1; } //从main开始至此,A B process代码一样,都是获取名为"Global\\MyFileMappingObject"的共享内存的指针 //以下代码,B不停写共享内存pBuf while(1) { TCHAR s[BUF_SIZE]; cout<<"B process: plz input sth. to be transfered to A process."<
>s; memcpy((PVOID)pBuf, s, BUF_SIZE); }}

 

转载地址:http://qtiti.baihongyu.com/

你可能感兴趣的文章
C语言应用题——如何确定跳水排名
查看>>
C语言实现小游戏——三子棋(Three Peices Chess)
查看>>
使用gdb调试多进程与多线程程序
查看>>
linux:进程组&作业&会话—concept&distinction&contact
查看>>
linux:终端(Terminal)基本概念&终端登录过程详解
查看>>
linux:守护进程&模拟实现mydaemon
查看>>
linux:作业控制&作业规划进程crond
查看>>
用arp.sh脚本文件抓取局域网内所有主机的IP和MAC地址
查看>>
MAC协议之CRC校验码
查看>>
NAT&代理服务器技术调研
查看>>
XShell初体验—连接VMware虚拟机
查看>>
网络端口服务(PortsService)介绍
查看>>
IO概念&5种IO模型介绍
查看>>
socketpair创建双向pipe
查看>>
linux:文件描述符重定向dup&dup2
查看>>
小白的福音—秒懂UDP协议&TCP协议
查看>>
详解TCP协议中控制位及URG&PSH的区别
查看>>
总结TCP协议中的定时器
查看>>
图解TCP—3次握手&4次挥手
查看>>
I/O多路转接之poll
查看>>