全局文件
#ifndef DEFINE_H
#define DEFINE_H
#include<QString>
#include <windows.h>
#include <iostream>
#include <string>
typedef struct
{
short dataType;
short width;
short height;
}MessageData;
const wchar_t *share_memory_name=L"shareMemory0";
const wchar_t *hMutex=L"DateIsReady";
const int share_memory_size=1024*10;
#endif // DEFINE_H
进程1
#include "mainwindow.h"
#include <QApplication>
#include "Define.h"
#include <windows.h>
#include <iostream>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
HANDLE hMapFile=CreateFileMapping(
INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
share_memory_size,
share_memory_name
);
if(hMapFile==nullptr)
{
qDebug()<<QObject::tr("开辟内存失败");
return -1;
}
LPVOID pBuf=MapViewOfFile(
hMapFile,
FILE_MAP_ALL_ACCESS,
0,0,share_memory_size
);
if(pBuf==nullptr)
{
qDebug()<<QObject::tr("映射内存失败");
CloseHandle(hMapFile);
return -1;
}
HANDLE hmutex=CreateMutex(NULL,false,hMutex);
if(hmutex==nullptr)
{
qDebug()<<QString("lock create fail");
return -1;
}
else
{
qDebug()<<QString("lock create succ");
}
while(1)
{
DWORD ts=WaitForSingleObject(hmutex,INFINITE);
if(ts==WAIT_OBJECT_0)
{
MessageData data0;
data0.dataType=1;
data0. width=200;
data0. height=230;
// ZeroMemory(pBuf,share_memory_size);
memcpy(pBuf,&data0,sizeof(MessageData));
Sleep(1000);
ReleaseMutex(hmutex);
}
}
return a.exec();
}
进程2
#include "mainwindow.h"
#include <QApplication>
#include "Define.h"
#include<QString>
#include <windows.h>
#include <iostream>
#include <string>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
HANDLE hMapFile1=CreateFileMapping(
INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
share_memory_size,
share_memory_name
);
if(hMapFile1==nullptr)
{
qDebug()<<QObject::tr("开辟内存失败");
return -1;
}
LPVOID pBuf1=MapViewOfFile(
hMapFile1,
FILE_MAP_ALL_ACCESS,
0,0,share_memory_size
);
if(pBuf1==nullptr)
{
qDebug()<<QObject::tr("映射内存失败");
CloseHandle(hMapFile1);
return -1;
}
while(1)
{
HANDLE hmutex1=OpenMutex(SYNCHRONIZE,false,hMutex);
//HANDLE hmutex1=CreateMutex(NULL,false,hMutex);
if(hmutex1==nullptr)
{
qDebug()<<QObject::tr("锁失败")<<123;
} else
{
qDebug()<<QObject::tr("锁成功")<<456;
DWORD ts1=WaitForSingleObject(hmutex1,INFINITE);
if(ts1==WAIT_OBJECT_0)
{
//4.读取数据
MessageData data0;
memcpy(&data0,pBuf1,sizeof(MessageData));
qDebug()<<"内容"<<data0.width;
ReleaseMutex(hmutex1);
}
}
}
return a.exec();
}