gpt4 book ai didi

c++ - 如何检查 WriteFile 函数是否完成

转载 作者:行者123 更新时间:2023-11-30 04:25:40 27 4
gpt4 key购买 nike

我想检查 WriteFile 函数是否已完成写入 UART,以便我可以在同一个 ComDev 上调用 ReadFile 而不会导致异常。

似乎WriteFile function可以在写入完成之前返回。

BOOL WriteCommBlock(HANDLE * pComDev, char *pBuffer , int BytesToWrite)
{
while(fComPortInUse){}

fComPortInUse = 1;

BOOL bWriteStat = 0;
DWORD BytesWritten = 0;
COMSTAT ComStat = {0};
OVERLAPPED osWrite = {0,0,0};

if(WriteFile(*pComDev,pBuffer,BytesToWrite,&BytesWritten,&osWrite) == FALSE)
{
short Errorcode = GetLastError();
if( Errorcode != ERROR_IO_PENDING )
short breakpoint = 5; // Error

Sleep(1000); // complete write operation TBD

fComPortInUse = 0;
return (FALSE);
}


fComPortInUse = 0;
return (TRUE);
}

我使用 Sleep(1000) 作为解决方法,但我该如何等待合适的时间?

最佳答案

您可以创建一个事件,将其存储在您的重叠结构中并等待它发出信号。像这样(未经测试):

BOOL WriteCommBlock(HANDLE * pComDev, char *pBuffer , int BytesToWrite)
{
while(fComPortInUse){}

fComPortInUse = 1;

BOOL bWriteStat = 0;
DWORD BytesWritten = 0;
COMSTAT ComStat = {0};
OVERLAPPED osWrite = {0,0,0};
HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

if (hEvent != NULL)
{
osWrite.hEvent = hEvent;
if(WriteFile(*pComDev,pBuffer,BytesToWrite,&BytesWritten,&osWrite) == FALSE)
{
short Errorcode = GetLastError();
if( Errorcode != ERROR_IO_PENDING )
short breakpoint = 5; // Error

WaitForSingleObject(hEvent, INFINITE);

fComPortInUse = 0;
return (FALSE);
}
CloseHandle(hEvent);
}


fComPortInUse = 0;
return (TRUE);
}

请注意,根据您尝试执行的其他操作,简单地调用 WaitForSingleObject() 可能不是最好的主意。 INFINITE 超时也不会。

关于c++ - 如何检查 WriteFile 函数是否完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12013161/

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