异常输入62;9;c62;9;c62;9;c62;9;c在向标准输出写入缓冲区后出现在shell中



目标是读取文件并将缓冲区直接写入标准输出,以便可以将其用于进一步处理。对于文本文件、图像和pdf文件,这是意料之中的。但是当读取pdf文件时,shell输入中显示了一个奇怪的输入,即:62;9;c62;9;c62;9;我在Ubuntu 14.04.3 LTS(14.04)上编译了test.c。

user@user-virtualmachine:~$./test
<prints binary data here
...
...
end of binary data>
user@user-virtualmachine:~$62;9;c62;9;c62;9;c62;9;c

当我检查md5sum时,它是匹配的,所以没有什么奇怪的:

md5sum paper.pdf
5152a6c5b7deb364385fb3dd27c586db     paper.pdf
./test | md5sum
5152a6c5b7deb364385fb3dd27c586db     -

我试着在网上查了一下,它说一些二进制数据可能会导致shell在将其写入标准输出时以意想不到的方式运行。这个问题能解决吗?代码如下:

Test.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
    ssize_t bytes_read;
    char buffer[1024];
    int fd;
    fd = open("paper.pdf", O_RDONLY);
    if(fd < 0) {
     perror("Error in reading file");
     exit(1);
    }
    do {
     bytes_read = read(fd, buffer, 1024);
     if(bytes_read > 0) {
         write(fileno(stdout), buffer, bytes_read);
     }
    } while(bytes_read > 0);
    close(fd);
    return 0;
}

PDF文件是二进制文件。虽然它们可以包含文本,但它们可以并且确实包含非文本数据。

要解决这个问题:不要将二进制数据转储到shell的输出。二进制数据来自哪里并不重要——试试cat /usr/bin/bash。你会得到相同的结果。要防止它"弄乱"shell的输出,唯一的方法就是不要这样做。

最新更新