C++进程间共享数据实例
时间:2021-06-29 08:27:54|栏目:C代码|点击: 次
本文实例讲述了C++进程间共享数据的实现方法,分享给大家供大家参考。具体实现方法如下:
复制代码 代码如下:
int main(int argc, char *argv[])
{
//RecursiveDelete("C:\\20_128\\");
//SelfRun("runModel");
//进程间内存共享
LPCTSTR lpName= "hello";
LPCTSTR lpContent = "123456";
HANDLE hMap = ::OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, lpName);
if (NULL == hMap) //打开失败
{
//创建
hMap = ::CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_EXECUTE_READWRITE, 0, strlen(lpContent), lpName);
if (hMap == NULL)
{
return -1;
}
//写入
LPVOID lpBase = ::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
strcpy((char*)lpBase, lpContent);
printf("write %s\n", lpContent);
}
else
{
//打开成功就只读取
LPVOID lpBase = ::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
if (lpBase == NULL)
{
return -1;
}
printf("read %s\n",(char*)lpBase);
}
getchar();
return 0;
}
{
//RecursiveDelete("C:\\20_128\\");
//SelfRun("runModel");
//进程间内存共享
LPCTSTR lpName= "hello";
LPCTSTR lpContent = "123456";
HANDLE hMap = ::OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, lpName);
if (NULL == hMap) //打开失败
{
//创建
hMap = ::CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_EXECUTE_READWRITE, 0, strlen(lpContent), lpName);
if (hMap == NULL)
{
return -1;
}
//写入
LPVOID lpBase = ::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
strcpy((char*)lpBase, lpContent);
printf("write %s\n", lpContent);
}
else
{
//打开成功就只读取
LPVOID lpBase = ::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
if (lpBase == NULL)
{
return -1;
}
printf("read %s\n",(char*)lpBase);
}
getchar();
return 0;
}
希望本文所述对大家的C++程序设计有所帮助。
上一篇:标准C++类string的Copy-On-Write技术
栏 目:C代码
下一篇:C++日志记录类实例解析
本文标题:C++进程间共享数据实例
本文地址:http://www.codeinn.net/misctech/149877.html