2

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!

Zweikeks
  • 300
  • 1
  • 11
  • 1) I figured out that this is an old Windows problem. The port is not set up correctly. The timeouts must be set. And 'mode' on the command line messes things up. Now I call SetCommState() and SetCommTimeouts() directly in my program. Thus freopen ("COM1", "r", stdin) alone does work now but the combination - redirecting both, stdout AND stdin, still does not. – Zweikeks Jul 27 '15 at 13:42

1 Answers1

0

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));
  • Thanks Felix. I gave it a try. Didn't work so far. But I will have to look further into it. – Zweikeks Jul 26 '15 at 06:06
  • 1
    Ah - it is working. Thanks a lot! For restoring the original stdin/out fd see here: [C restore stdout to terminal](http://stackoverflow.com/questions/11042218/c-restore-stdout-to-terminal) – Zweikeks Jul 27 '15 at 16:53