在 Win32 中侦听通信端口和标准输入
我正在尝试编写一个小实用程序,使用 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);
}
}
知道我在这里做错了什么吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我没记错的话,您需要使用重叠 I/O 进行串行端口访问才能使一切正常工作。 这通常意味着您需要创建一个单独的线程来处理串行端口输入。 我不记得具体原因,但使用
WaitForMultipleObjects
会出现串行端口问题。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.WaitForMultiplObjects 的文档表示以下内容是可等待的:
请注意,未提及文件和通信端口。
The docs for WaitForMultiplObjects says that the following are waitable:
Notice that files and comms ports are not mentioned.