【发布时间】:2013-11-17 03:20:52
【问题描述】:
Windows Embedded Compact。
Trying to send and receive a message with MsgQueue.
看起来写入正常,但读取给出了不正确的参数错误。
任何想法缺少什么?
我不确定创建队列功能。它说必须调用两次才能获得读取或写入句柄 - 对吗?
int main()
{
MSGQUEUEOPTIONS options = {0};
options.dwSize = sizeof(options); //
options.dwFlags = MSGQUEUE_NOPRECOMMIT;
options.dwMaxMessages = 10000; // msg max for queue
options.cbMaxMessage = 50; // max number of bytes in each msg
options.bReadAccess = TRUE; // read
HANDLE hRead = CreateMsgQueue(LPCWSTR("MSG_QUEUE"), &options);
if ( hRead == NULL )
{
printf("CreateMsgQueue hRead failed! Err code: %d\n", GetLastError());
}
// Thread A will read msg queue
HANDLE hTg = CreateThread(NULL, 0, threadA, hRead, 0, 0);
if ( NULL == hTg )
{
printf("CreateThread failed - A!\n");
return 1;
}
Sleep(1000); //give time before sending msg
options.bReadAccess = FALSE; // write to
HANDLE hWrte = CreateMsgQueue(LPCWSTR("MSG_QUEUE"), &options);
if ( hWrte == NULL )
{
printf("CreateMsgQueue hWrte failed! Err code: %d\n", GetLastError());
}
// Thread B write to queue
HANDLE hTt = CreateThread(NULL, 0, threadB, hWrte, 0, 0);
if ( NULL == hTt )
{
printf("CreateThread failed - B!\n");
return 1;
}
// quit on <ENTER> key
getchar();
}
DWORD WINAPI threadB(LPVOID lpParameter)
{
HANDLE msgH = HANDLE(lpParameter);
if ( msgH == NULL)
{
printf("Null handle in write!\n");
}
char message[10] = "ABCDEFGHI";
printf("Size of message sent: %d bytes\n", sizeof(message));
// know that a queue is not full and that it's safe to write
WaitForSingleObject(msgH, INFINITE);
BOOL ret = WriteMsgQueue(
msgH,
&message,
sizeof(message),
INFINITE,
NULL);
if ( ret == FALSE )
{
printf("WriteMsgQueue failed! Err code: %d\n", GetLastError());
}
return 0;
}
DWORD WINAPI threadA(LPVOID lpParameter)
{
HANDLE hQ = HANDLE(lpParameter);
if ( hQ == NULL )
{
printf("null handle in read!\n");
}
char readIn[50] = {0};
LPDWORD numRead = 0;
//DWORD flag;
// need to wait on sinfle object
WaitForSingleObject(hQ, INFINITE);
BOOL ret = ReadMsgQueue(
hQ,
&readIn,
DWORD(sizeof(readIn)),
numRead,
INFINITE,
NULL
);
if ( ret == FALSE )
{
printf(" ReadMsgQueue failed! Err code: %d\n", GetLastError());
}
printf("Size received: %d\n", numRead);
printf("Msg Received: %s\n", readIn);
return 0;
}
编辑
这是@WhozCraig 之后的工作读取功能,并且发现了另一个问题,以防其他人需要这个:
DWORD WINAPI threadA(LPVOID lpParameter)
{
HANDLE hQ = HANDLE(lpParameter);
if ( hQ == NULL )
{
printf("null handle in read!\n");
}
char readIn[50] = {0};
DWORD numRead = 0;
DWORD flag;
// need to wait on sinfle object
WaitForSingleObject(hQ, INFINITE);
BOOL ret = ReadMsgQueue(
hQ,
&readIn,
sizeof(readIn),
&numRead,
INFINITE,
&flag
);
if ( ret == FALSE )
{
printf(" ReadMsgQueue failed! Err code: %d\n", GetLastError());
}
printf("Size received: %d\n", numRead);
printf("Msg Received: %s\n", readIn);
return 0;
}
【问题讨论】:
-
什么是停止
main()完成并在启动两个线程后返回程序终止?就我所见。。什么都没有。您可能希望等待这两个创建的线程句柄。 -
@whozcraig:抱歉,试图取出多余的东西。我有 // 退出
键 getchar();
标签: c# c++ c windows windows-ce