【问题标题】:Listening on a comm port and stdin in Win32在 Win32 中侦听通信端口和标准输入
【发布时间】:2010-10-20 19:08:45
【问题描述】:

我正在尝试编写一个使用 Win32 API 将 stdin/stdout 映射到串行端口(某种命令行终端仿真器)的小实用程序。我有以下代码,我认为它应该可以工作,但它似乎没有从串口正确接收通知:

HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
HANDLE hCom = CreateFile(com_name, GENERIC_READ | GENERIC_WRITE, NULL, NULL, OPEN_EXISTING, 0, NULL);

/* check for errors opening the serial port, configure, set timeouts, etc */

HANDLE hWaitHandles[2];
hWaitHandles[0] = hStdin;
hWaitHandles[1] = hCom;
DWORD dwWaitResult = 0;
for (;;) {
    dwWaitResult = WaitForMultipleObjects(2, hWaitHandles, FALSE, INFINITE);
    if(dwWaitResult == WAIT_OBJECT_0)
    {
        DWORD bytesWritten;
        int c = _getch();
        WriteFile(hCom, &c, 1, &bytesWritten, NULL);
        FlushConsoleInputBuffer( hStdin);
    } else if (dwWaitResult == WAIT_OBJECT_0+1) {
        char byte;
        ReadFile(hCom, &byte, 1, &bytesRead, NULL);
        if (bytesRead)
            printf("%c",byte);
    }
}

有什么想法我在这里做错了吗?

【问题讨论】:

    标签: winapi serial-port polling waitformultipleobjects


    【解决方案1】:

    如果我没记错的话,您需要使用重叠 I/O 进行串行端口访问,以使一切正常工作。这通常意味着您需要创建一个单独的线程来处理串口输入。具体原因我不记得了,但是使用WaitForMultipleObjects 的串口有问题。

    【讨论】:

    • hrmm。我试图避免这样做;对于这样一个(看似?)简单的任务,似乎有点矫枉过正。
    【解决方案2】:

    WaitForMultiplObjects 的文档说以下是可等待的:

    * Change notification
    * Console input
    * Event
    * Memory resource notification
    * Mutex
    * Process
    * Semaphore
    * Thread
    * Waitable timer
    

    请注意,未提及文件和通讯端口。

    【讨论】:

    • 是的;我后来意识到了这一点。我还在想posix的select()。从技术上讲,WaitForMultipleObjects 是在传递给 ReadFile() 或 WriteFile() 的重叠事件上完成的,而不是在端口本身上。
    猜你喜欢
    • 1970-01-01
    • 2014-07-31
    • 2014-10-13
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多