1

I have a Bash script work.sh that get something from STDIN and echo it to STDOUT.

I also have a C programme, return_input, that also get something from STDIN and printf to STDOUT

But when I chain them this way:

./work.sh |./return_input

printf in return_input only output to screen when exiting. Why?

Simplified:

[root@ test]# cat work.sh
#!/bin/bash
for i in {1..5}
do
   echo test
   read
done

Output of cat return_input.c,

#include <stdio.h>

void return_input (void){
    char array[30];
    gets (array);
    printf("%s\n", array);
    printf("%#p\n", *(long *)(array+40));
}

main() {
    while(1 == 1)return_input();
    return 0;
}
3
  • @James,When is flush necessary? Commented Apr 18, 2011 at 14:05
  • Is it just me, or is return_input just reading once and work.sh writing things as it goes along? Seems like return_input should be reading work.sh's output in some kind of loop. Commented Apr 18, 2011 at 14:27
  • @clintp,I've modified the code now:) Commented Apr 18, 2011 at 14:39

2 Answers 2

5

All I/O operations are usually buffered. This is why you get the output only after you program finishes if there are not much data to overflow the buffer and output during the execution.

You can use fflush function which forces to finish I/O operation and clear buffers if you want to see output in the "real time"

Sign up to request clarification or add additional context in comments.

Comments

1

You should post some code.

Try making sure that the output is flushed (using fflush(stdout); in C after you've written to it), and/or that the text contains line-feeds since typically those force the output to be flushed.

Otherwise the output might be "stuck" in a buffer, which is an optimization rather than sending single bytes across the pipeline between the processes.

4 Comments

"When opened, a stream is fully buffered if and only if it can be determined not to refer to an interactive device." (C90). STDOUT should be an interactive device and the flush happening at least at each \n.
I've provided a simplified example above:)
"Forcing" may be done by the 'stdbuf' utility. See 'man stdbuf'.
But seems in my case it's buffered by work.sh,not in c programe?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.