如何在程序运行到 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(或任何其他程序)将在打印时接收每一行。