如何将标准输出重定向到 COM 端口

How to redirect stdout to a COM Port

谁能告诉我如何将标准输出重定向到 C 中的 COM 端口?

正在 Windows 机器上工作。在线阅读 Microsoft 使用设备文件和设备关键字,例如控制台的 CON。他们也有一些用于 COM 端口,'COM1'。

然而,这样做似乎没有效果? >> freopen( "COM5", "w", stdout );

感谢您的帮助。

cjg199

COMx 是串行设备,必须进行配置。在引擎盖下,putty(或 kermit 或超级终端)会配置波特率、大小、奇偶校验和停止位。

并且应该以独占访问权限打开 COM 设备。这意味着如果一个putty已经控制了线路,你将无法在另一个程序中打开它。

所以正常的用法是:

  • 打开设备(CreateFile WinAPI函数)
  • 配置设备(GetCommState - SetCommState
  • 获取 windows 句柄 (_open_osfhandle)
  • 的文件描述符
  • 使用 dup2
  • 将文件描述符复制到 fd 1

在那之后,您应该能够写入 fd 1 的标准输出并在串行线上获得输出。

有限代码(没有错误处理,未经测试,因为我目前没有串口设备):

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

参考资料: