有人能告诉我如何将stdout重定向到C中的COM端口吗?
在Windows计算机上工作。在线阅读Microsoft使用设备文件和设备关键字,例如CON用于控制台。它们也有一些COM端口,'COM1'。
然而,这样做似乎没有用? >> freopen( "COM5", "w", stdout );
感谢您的帮助。
cjg199
答案 0 :(得分:0)
COMx是串行设备,必须进行配置。在引擎盖下,putty(或kermit或hyperterminal)确实配置了波特率,大小,奇偶校验和停止位。
应该使用独占访问权限打开COM设备。这意味着如果一个putty已经控制了该行,你将无法在另一个程序中打开它。
所以正常用法是:
CreateFile
WinAPI功能)GetCommState
- SetCommState
)_open_osfhandle
)dup2
之后,你应该能够写入到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);
参考文献: