[erlang-questions] "Port reading stdout from external program"

Stanislaw Klekot erlang.org@REDACTED
Wed Nov 16 20:43:31 CET 2016

On Wed, Nov 16, 2016 at 08:06:03PM +0100, Alex Feng wrote:
> Hi,
> I am using an port to communicate with an external program, I would like to
> fetch each output from the external problem.
> But I have problem to fetch the output when the external problem runs into
> waiting input," scanf " for example.
> Here is an example to communicate with a simple C program.
> I need to fetch the prompt line("Please input you name") from Port in order
> to interact with C code,  but with "scanf" added in C code, I couldn't
> fetch it from Port.
> Does anyone know why is that ?  Any advice and suggestions will be greatly
> appreciated.
> C code:
> int main()
> {
>   char str[10];
>   printf("Please input you name:");  //Prompt line
>   scanf ("%9s",str);  // with this line, port can not read the output from this program.
>   return 1;
> }

It's because STDOUT buffering differs between running things in terminal
directly and running them with STDOUT redirected somewhere. You can see
it yourself by first running this "a.out" in shell, and then running it
redirected to cat: "a.out | cat". In the latter case you won't get

You need to call fflush() to flush anything buffered by printf() (see
its man page for details).

Stanislaw Klekot

More information about the erlang-questions mailing list