COMx 是串行设备,必须进行配置。在底层,putty(或 kermit 或超级终端)会配置波特率、大小、奇偶校验和停止位。
并且应该以独占访问方式打开 COM 设备。这意味着如果腻子已经控制了线路,您将无法在其他程序中打开它。
所以正常的用法是:
- 打开设备(
CreateFileWinAPI函数)
- 配置设备 (
GetCommState - SetCommState)
- 获取窗口句柄的文件描述符 (
_open_osfhandle)
- 用
dup2复制文件描述符到fd 1
之后,您应该能够写入到 fd 1 的 stdout 并在串行线上获得输出。
有限的代码(没有错误处理和未经测试,因为我目前没有串口设备):
HANDLE hCom;
DCB dcb;
BOOL fSuccess;
int fd, cr;
hCom = CreateFile( TEXT("COM5"), GENERIC_READ | GENERIC_WRITE,
0, // exclusive access
NULL, // default security attributes
OPEN_EXISTING, 0, NULL);
// Build on the current configuration, and skip setting the size
// of the input and output buffers with SetupComm.
SecureZeroMemory(&dcb, sizeof(DCB));
dcb.DCBlength = sizeof(DCB);
fSuccess = GetCommState(hCom, &dcb);
// Fill in DCB: 57,600 bps, 8 data bits, no parity, and 1 stop bit - adapt to YOUR config
dcb.BaudRate = CBR_57600; // set the baud rate
dcb.ByteSize = 8; // data size, xmit, and rcv
dcb.Parity = NOPARITY; // no parity bit
dcb.StopBits = ONESTOPBIT; // one stop bit
fSuccess = SetCommState(hCom, &dcb);
fd = _open_osfhandle(hCom, 0);
cr = _dup2(fd, 1);
参考资料: