Hello.
OS: WinXP SP3
IDE: MS Visual C++ 2010 Express Edition
Problem: Transmitter program can't write to mailslot. CreateFile works fine, WriteFile causes error №6 - "invalid handle". Receiver program works fine ("Process Explorer" tool shows me that mailslot exists).
Receiver code:
hMailslot = CreateMailslot(L"\\\\.\\mailslot\\MySendRecv", 0, 2000, NULL);
if (hMailslot == INVALID_HANDLE_VALUE)
wcout << L"Can't start server" << endl;
else
{
wcout << L"Server started successfully" << endl;
DWORD NextSize;
DWORD MessageCount;
OVERLAPPED ol;
while (true)
{
auto result = GetMailslotInfo(hMailslot, 0, &NextSize, &MessageCount, NULL);
if (!result)
wcout << "Can't get mailslot info" << endl;
else if (NextSize == MAILSLOT_NO_MESSAGE)
; else
while (MessageCount > 0)
{
wchar_t* sMsgBuffer = new wchar_t[NextSize+1];
SecureZeroMemory(sMsgBuffer, sizeof(wchar_t)*(NextSize+1) );
DWORD NumerOfBytesRead;
result = ReadFile(hMailslot, sMsgBuffer, NextSize, &NumerOfBytesRead, &ol);
if (!result)
{
wcout << "Can't read message" << endl;
delete sMsgBuffer;
break;
}
MailslotCallback(sMsgBuffer);
delete sMsgBuffer;
result = GetMailslotInfo(hMailslot, 0, &NextSize, &MessageCount, NULL);
if (!result)
{
wcout << "Can't get mailslot info" << endl;
break;
}
}
Sleep(2000);
}
}
return 0;
Transmitter code:
void MailslotSend(wchar_t* sMailslotName, void* pData, size_t ndataSize)
{
HANDLE hFile;
hFile = CreateFile(sMailslotName,
GENERIC_WRITE,
FILE_SHARE_READ,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
wcout << "Can't begin sending data - error " << GetLastError() << endl;
return;
}
DWORD NumberOfBytesWritten;
OVERLAPPED ol;
auto fResult = WriteFile(hFile, pData, ndataSize, &NumberOfBytesWritten, &ol);
if (!fResult)
wcout << "Data send failed - error " << GetLastError() << endl;
else
wcout << "Data send ok" << endl;
CloseHandle(hFile);
}
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t msg[64] = {0};
wcout << "Enter message: ";
wcin >> msg;
while ( lstrcmp(L"", msg) != 0 )
{
MailslotSend(L"\\\\.\\mailslot\\MySendRecv", msg, 64*sizeof(wchar_t) );
wcout << "Enter message: ";
ZeroMemory(msg, 64*sizeof(wchar_t) );
wcin >> msg;
}
return 0;
}