I am using the typical puts
, printf
and getchar
functions in my Windows console application. Now I would like to redirect the stdout and the stdin to a COM port.
Redirecting stdout alone is working fine:
freopen ("COM1", "w", stdout);
Afterwards all output is going to COM1 as expected.
However with the input I am facing two problems:
freopen ("COM1", "r", stdin);
1) Only stdin redirected, COM1 opens ok. But getchar
(or similar functions) do not return characters from COM1. getchar
does never return. I tried several modes (r, r+, rb, even w).
2) If stdout is already redirected to COM1, the call to freopen for stdin fails (returns NULL). Likely because COM1 is already in use for stdout.
Environment: Console Application, Windows 7, MinGW
Am I doing something wrong? Is there another (or better) way to accomplish the redirection?
Thanks for any help!
I can't test it right now because I only have a virtual windows machine reachable by RDP, without serial connection, but still, shouldn't something like this work?
int comfd = open("COM1", O_RDWR);
dup2(comfd, 0);
dup2(comfd, 1);
Or, if you dislike hardcoded fds
int comfd = open("COM1", O_RDWR);
dup2(comfd, fileno(stdin));
dup2(comfd, fileno(stdout));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.