winapi - CreateFile() 返回 INVALID_HANDLE_VALUE 但 GetLastError() 是 ERROR_SUCCESS

标签 winapi serial-port createfile iocp getlasterror

我正在使用 CreateFile() 打开一个串口.我有一个测试用例(太复杂而无法重新分发),它始终导致 CreateFile()返回 INVALID_HANDLE_VALUEGetLastError()返回 ERROR_SUCCESS .从表面上看,只有一个线程在另一个端口关闭它的同时打开该端口,才会发生此错误。打开端口的线程遇到了这个问题。

我不知道这是否有区别,但稍后在代码中我使用 CreateIoCompletionPort 将端口与 CompletionPort 相关联。 .

这是我的代码:

HANDLE port = CreateFile(L"\\\\.\\COM1",
                         GENERIC_READ | GENERIC_WRITE,
                         0,                    // must be opened with exclusive-access
                         0,                    // default security attributes
                         OPEN_EXISTING,        // must use OPEN_EXISTING
                         FILE_FLAG_OVERLAPPED, // overlapped I/O
                         0);                   // hTemplate must be NULL for comm devices
if (port == INVALID_HANDLE_VALUE)
{
    DWORD errorCode = GetLastError();
    cerr << L"CreateFile() failed with error: " << errorCode << endl;
}

我很确定这种事情不应该发生。我做错了什么吗?如何让 API 返回正确的结果?

更多详情 :此代码取自我开发的串行端口库:JPeripheral

这是实际的(未经 sanitizer 的)源代码:
JLong SerialChannel::nativeOpen(String name)
{
    cerr << "nativeOpen(" << name << ")" << endl;
    wstring nameWstring = name;
    HANDLE port = CreateFile((L"\\\\.\\" + nameWstring).c_str(),
        GENERIC_READ | GENERIC_WRITE,
        0,                                          // must be opened with exclusive-access
        0,                                          // default security attributes
        OPEN_EXISTING,                  // must use OPEN_EXISTING
        FILE_FLAG_OVERLAPPED,       // overlapped I/O
        0);                                         // hTemplate must be NULL for comm devices
    cerr << "nativeOpen.afterCreateFile(" << name << ")" << endl;
    cerr << "port: " << port << ", errorCode: " << GetLastError() << endl;
    if (port == INVALID_HANDLE_VALUE)
    {
        DWORD errorCode = GetLastError();

        switch (errorCode)
        {
            case ERROR_FILE_NOT_FOUND:
                throw PeripheralNotFoundException(jace::java_new<PeripheralNotFoundException>(name, Throwable()));
            case ERROR_ACCESS_DENIED:
            case ERROR_SHARING_VIOLATION:
                throw PeripheralInUseException(jace::java_new<PeripheralInUseException>(name, Throwable()));
            default:
            {
                throw IOException(jace::java_new<IOException>(L"CreateFile() failed with error: " +
                    getErrorMessage(GetLastError())));
            }
        }
    }

    // Associate the file handle with the existing completion port
    HANDLE completionPort = CreateIoCompletionPort(port, ::jperipheral::worker->completionPort, Task::COMPLETION, 0);
    if (completionPort==0)
    {
        throw AssertionError(jace::java_new<AssertionError>(L"CreateIoCompletionPort() failed with error: " +
            getErrorMessage(GetLastError())));
    }
    cerr << "nativeOpen.afterCompletionPort(" << name << ")" << endl;

    // Bind the native serial port to Java serial port
    SerialPortContext* result = new SerialPortContext(port);
    cerr << "nativeOpen.afterContext(" << name << ")" << endl;
    return reinterpret_cast<intptr_t>(result);
}

这是我得到的实际输出:
nativeOpen(COM1)
nativeOpen.afterCreateFile(COM1)
port: 00000374, errorCode: 0
nativeOpen.afterCompletionPort(COM1)
nativeOpen.afterContext(COM1)
[...]
nativeOpen(COM1)
nativeOpen.afterCreateFile(COM1)
port: FFFFFFFF, errorCode: 0
java.io.IOException: CreateFile() failed with error: The operation completed successfully.

最佳答案

 HANDLE port = CreateFile(...);
 cerr << "nativeOpen.afterCreateFile(" << name << ")" << endl;
 cerr << "port: " << port << ", errorCode: " << GetLastError() << endl;
 if (port == INVALID_HANDLE_VALUE)
 {
    DWORD errorCode = GetLastError();

cerr 的输出在幕后调用 winapi 调用。这将重置 GetLastError() 返回的线程错误值。使固定:
 HANDLE port = CreateFile(...);
 int err = GetLastError();
 // etc, use err instead...

关于winapi - CreateFile() 返回 INVALID_HANDLE_VALUE 但 GetLastError() 是 ERROR_SUCCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7665384/

相关文章:

c++ - 使用 CreateFile 访问驱动器分区

c++ - C++ 中的 Win32-Api CreateFile(...) 失败

python - 读取 Windows 文件而不阻止其他进程写入该文件

c++ - 版本信息表 通过 UpdateResource 更改 pe 文件?

winapi - 为什么有时会用空矩形调用 WM_PAINT?

c++ - 从 std::ofstream 获取句柄

windows - 如何在 Windows 中获取 COM 端口的友好名称?

c++ - QtSerialPort 在错误的线程中实例化,导致信号/插槽失败

c - Windows API的CreateFile()中OPEN_ALWAYS和CREATE_ALWAYS的区别

bash - grep 从 shell 脚本内的串行端口输入 5 秒