gpt4 book ai didi

c++ - 调用CreateFile打开串口 "comX"时如何设置限时?

转载 作者:行者123 更新时间:2023-11-30 02:26:27 24 4
gpt4 key购买 nike

我有一个蓝牙串行端口来与硬件通信。如果硬件没有上电,使用“CreateFile”会使线程阻塞,5-6秒后会报错“The semaphore timeout period has expired”。是否可以通过设置超时时间来花费更少的时间来获得使用“CreateFile”的结果?谢谢。

最佳答案

不幸的是,CreateFile 只是同步的 api,它不带任何超时参数(即使是低级别的 ZwCreateFile 也没有这个功能)。

在这种情况下您最多可以做些什么 - 将调用 CreateFile 移动到单独的线程,如果一段时间后它没有完成 - 调用 CancelSynchronousIo对于这个线程。这可以帮助但只能 - I/O Completion/Cancellation Guidelines

All IRPs (including Create) that can take an indefinite amount of time must be able to be cancelled

但是 I/O 子系统依赖于驱动程序 - 所以结果将取决于 - 是处理串口实现 IRP_MJ_CREATE 取消的驱动程序

struct OPEN_PACKET 
{
PCWSTR lpFileName;
HANDLE hFile;
DWORD error;
DWORD dwDesiredAccess;
DWORD dwShareMode;
DWORD dwCreationDisposition;
DWORD dwFlagsAndAttributes;
};

DWORD WINAPI OpenComPort(OPEN_PACKET* op)
{
HANDLE hFile = CreateFile(op->lpFileName, op->dwDesiredAccess, op->dwShareMode,
NULL, op->dwCreationDisposition,op->dwFlagsAndAttributes, NULL);

op->error = hFile == INVALID_HANDLE_VALUE ? GetLastError() : NOERROR;
op->hFile = hFile;

return GetLastError();// for possible use GetExitCodeThread but use op->error better
}

void testCC(PCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes)
{
OPEN_PACKET op = { lpFileName, INVALID_HANDLE_VALUE, ERROR_IO_PENDING,
dwDesiredAccess, dwShareMode, dwCreationDisposition, dwFlagsAndAttributes };

ULONG ticks = GetTickCount();

if (HANDLE hThread = CreateThread(NULL, PAGE_SIZE, (PTHREAD_START_ROUTINE)OpenComPort, &op, 0, NULL))
{
if (WaitForSingleObject(hThread, 1000) == WAIT_TIMEOUT)//1 sec for example
{
CancelSynchronousIo(hThread);
WaitForSingleObject(hThread, INFINITE);
}
CloseHandle(hThread);
}
else
{
op.error = GetLastError();
}

ticks = GetTickCount() - ticks;

WCHAR sz[256];
if (!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, op.error, 0, sz, RTL_NUMBER_OF(sz), NULL)) *sz = 0;
DbgPrint("[%u ms] hFile=%p err=%u %S\n", ticks, op.hFile, op.error, sz);

if (op.hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(op.hFile);
}
}

void ep()
{
testCC(L"\\\\server\\share\\1.txt", FILE_GENERIC_READ|FILE_GENERIC_WRITE, FILE_SHARE_VALID_FLAGS, OPEN_EXISTING, 0);
testCC(L"\\\\?\\globalroot\\systemroot\\notepad.exe", FILE_GENERIC_READ|FILE_GENERIC_WRITE, FILE_SHARE_VALID_FLAGS, OPEN_EXISTING, 0);
testCC(L"\\\\?\\globalroot\\systemroot\\notepad.exe", FILE_GENERIC_READ, FILE_SHARE_VALID_FLAGS, OPEN_EXISTING, 0);
}

然后我得到下一个结果:

[1000 ms] hFile=FFFFFFFFFFFFFFFF err=995 The I/O operation has been aborted because of either a thread exit or an application request.

[0 ms] hFile=FFFFFFFFFFFFFFFF err=5 Access is denied.

[0 ms] hFile=0000000000000154 err=0 The operation completed successfully.

关于c++ - 调用CreateFile打开串口 "comX"时如何设置限时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42848131/

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