How to pipe output of program as it runs into xxd?

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error How to pipe output of program as it runs into xxd? on this date .

I want to be able to see the output of my program in hex, as it runs, however if I pipe the output into xxd it will only print once the program has stopped running.

These are the things that that I’ve tried:

./a.out | while read LINE; do echo "$LINE" | xxd; done

./a.out | xxd

This is what my console looks like: (the arrows are my comments)

1 <-- input
2 <-- input
3 <-- input
4 <-- input
a <-- input (program ends after this input)
00000000: 6465 6667 0a                           defg.. <-- output
00000000: 6465 6667 0a                           defg.. <-- output
00000000: 6465 6667 0a                           defg.. <-- output
00000000: 6465 6667 0a                           defg.. <-- output

but this is what I want

1 <-- input
00000000: 6465 6667 0a                           defg.. <-- output
2 <-- input
00000000: 6465 6667 0a                           defg.. <-- output
3 <-- input
00000000: 6465 6667 0a                           defg.. <-- output
4 <-- input
00000000: 6465 6667 0a                           defg.. <-- output
a <-- input (program ends after this input)

(it’s a simple test program in which it will print a set string if a number is inputted else it will exit)

a.c program

#include <stdio.h>

int main() {
    
    const char test[7] = {0x64,0x65,0x66,0x67,'n',0x00};
    int testInteger;
    while(scanf("%d", &testInteger)){
        printf(test);
    }
}

Thanks in advance

Answer

By default, stdout is fully buffered when writing to a pipe, so read doesn’t receive anything until the output is flushed. This won’t happen until the program has written 4K bytes (almost 700 lines) or exits.

You can use stdbuf to alter the buffering.

stdbuf -oL a.out | xxd

-oL switches to line buffering, so xxd (or any other program) will receive each line as it’s printed.