gpt4 book ai didi

c - 从串行端口读取数据时发生 I/O 挂起错误

转载 作者:行者123 更新时间:2023-11-30 17:31:29 25 4
gpt4 key购买 nike

我有一个 C 程序,试图从 Windows 中的 COM 端口读取数据。我可以在 com 端口上写入数据,但无法读取数据。这是我的阅读功能?如果有人可以看一下并指出我正确的方向。我正在主方法中启动一个单独的线程

------main方法函数代码------

if(!SetCommMask(hSerial,eventFlags)){
printf("Error in setting the event maskwith error: %d \n",GetLastError());}
_beginthread(*readDataFromPort,0,NULL);

-----读取数据函数代码------

void readDataFromPort(void*)
{
DWORD dwReadResult;
bool waitOnRead = FALSE;
bool abContinue = TRUE;

memset(&ovRead,0,sizeof(ovRead));
ovRead.hEvent = CreateEvent(0,TRUE,0,0);
if(ovRead.hEvent == NULL){
fprintf(stderr,"Error creating overlapped event for reading");
}
//Reading data from port
while (true){
//Changed the overlap to NULL
if(WaitCommEvent(hSerial,&eventFlags,NULL)){
if(GetCommMask(hSerial,&dwMask)){
ResetEvent(ovRead.hEvent);
if(dwMask == EV_RXCHAR){
printf("character arrived");
}
}
memset(tmp,0,sizeof(tmp));

if(!ReadFile(hSerial, tmp, sizeof(tmp), NULL, &ovRead)){
if(GetLastError()!=ERROR_IO_PENDING){
printf("error io pending: Error is %d\n",GetLastError());
break;
}else{
waitOnRead=TRUE;
}
}
if(waitOnRead){
dwReadResult = WaitForSingleObject(ovRead.hEvent,10000);
switch(dwReadResult){
case WAIT_OBJECT_0:
if(!GetOverlappedResult(hSerial,&ovRead,&dwBytesRead,TRUE)){
printf("Damn error again :-(");
}else{
if(dwBytesRead>0){
++Rx;
printf("Tx - %d: Rx - %d\n",Tx,Rx);
printf("%s",tmp);
}
}
}
}
waitOnRead=FALSE;
}
if(strlen(tmp)>0 && inLoop){
writeDataToPort(*tmp);
}
}
CloseHandle(ovRead.hEvent);
_endthread();
}

> Blockquote

最佳答案

_beginthread(*readDataFromPort,0,NULL);

无论 SetComMask 结果如何,此代码片段都会启动线程,但如果您正在阅读,那么一定已经成功了。查看 MSDN 线程端口读/写的工作原理(VC5 编译直接开箱即用),上面的代码看起来非常相似,是一样的吗?

关于c - 从串行端口读取数据时发生 I/O 挂起错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24598825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com