邮件槽通信

来源:互联网 发布:mysql 图形化工具 mac 编辑:程序博客网 时间:2024/06/05 22:34

利用邮槽实现进程间通信(C++)

进程间通信,必须要能够像船一样,能够实现传递作用。邮槽,由此而生。

-----------------------------------server.cpp

//mailSlotMain.cpp

#include<iostream>
#include<atlbase.h>
#include<Winbase.h>


using namespace std;

int main(int argc ,char * argv)
{
HANDLE h_slot;
h_slot=::CreateMailslotA(
"\\\\.\\mailslot\\myslot",
0,
MAILSLOT_WAIT_FOREVER,
NULL);

if(h_slot==INVALID_HANDLE_VALUE)
{
::cout<<"h_slot created false"<<endl;
}else
{
::cout<<"h_slot created success!"<<endl;
char serverString[1024];
DWORD readtext;
if(::ReadFile(h_slot,serverString,sizeof(serverString),&readtext,NULL))
{

::cout<<"Readfile Success:"<<serverString<<endl;
::Sleep(1000);

}
else
{
::cout<<"Readfile false!"<<GetLastError<<endl;
}

}


//::cout<<serverString<<endl;


::CloseHandle(h_slot);
::Sleep(5000);
return 0;
}

-----------------------------------client.cpp

//clientSlotMain.cpp

#include<iostream>
#include<atlbase.h>
#include<WinBase.h>


using namespace std;


int main(int argc, char * argv)
{

HANDLE h_client;
h_client=::CreateFileA(
"\\\\.\\mailslot\\myslot",
GENERIC_ALL,/**很重要的设置,the set is very important */
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);

if(h_client==INVALID_HANDLE_VALUE)
{
::cout<<"h_client created false!"<<endl;
}
else
{
::cout<<"h_client created success!"<<endl;
}
DWORD writetext;
char clientString[]="client is sending data!";
if(
::WriteFile(
h_client,
clientString,
sizeof(clientString),
&writetext,
NULL
))
{
::cout<<"WriteFile success:"<<clientString<<endl;

::Sleep(1000);

}
else
{
::cout<<"WriteFile false: "<<GetLastError<<endl;
}

::CloseHandle(h_client);

::Sleep(5000);

return 0;
}