views:

359

answers:

2

I'm trying to write a small utility that maps stdin/stdout to a serial port (a command line terminal emulator of sorts) using the Win32 APIs. I have the following code, which I think ought to work, but it doesn't appear to be receiving notifications properly from the serial port:

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);
    }
}

Any ideas what I'm doing wrong here?

+1  A: 

If I remember correctly, you need to do serial port access using overlapped I/O for everything to work properly. This generally means that you need to create a separate thread to handle the serial port input. I don't remember why exactly, but using WaitForMultipleObjects has problems with serial ports.

Greg Hewgill
hrmm. I was trying to avoid doing that; seems like a bit of overkill for such a (seemingly?) simple task.
Mikeage
+1  A: 

The docs for WaitForMultiplObjects says that the following are waitable:

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

Notice that files and comms ports are not mentioned.

anon
Yep; I realized that later. I'm still thinking posix's select(). Technically, the WaitForMultipleObjects is done on the overlapped event passed to ReadFile() or WriteFile(), not on the port itself.
Mikeage