如何在程序运行到 xxd 时通过管道输出程序?

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

我希望能够在运行时以十六进制形式查看我的程序的输出,但是如果我将输出通过管道传输到 xxd,它只会在程序停止后打印 运行.

这些是我尝试过的东西:

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

./a.out | xxd

这是我的控制台的样子:(箭头是我的评论)

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

但这就是我想要的

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)

(这是一个简单的测试程序,如果输入一个数字,它会打印一个设置的字符串,否则它会退出)

a.c 节目

#include <stdio.h>

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

提前致谢

默认情况下,stdout 在写入管道时是完全缓冲的,因此 read 在输出被刷新之前不会收到任何东西。在程序写入 4K 字节(将近 700 行)或退出之前不会发生这种情况。

您可以使用 stdbuf 来改变缓冲。

stdbuf -oL a.out | xxd

-oL 切换到行缓冲,因此 xxd(或任何其他程序)将在打印时接收每一行。