为什么 read() 只 return stdin 的第一行?

Why does read() only return the first line of stdin?

我有一个 C 程序试图从标准输入读取最多 1024 个字节。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
    int MAX_SIZE = 1024;
    char *program = malloc(sizeof(char) * MAX_SIZE);

    int STDIN_FD = 0;

    int return_code = 0;

    int bytes_read = read(STDIN_FD, program, MAX_SIZE);
    if (bytes_read == -1) {
        printf("Could not read from stdin");
        return_code = 1;
    } else {
        printf("bytes read: %d\n", bytes_read);
        program[bytes_read] = '[=1=]';
        printf("program: %s\n", program);
    }

    free(program);

    return return_code;
}

我编译并运行它:

$ cat testfile.txt 
hello
world
$ gcc -Wall -std=c99 oneline.c 
$ cat testfile.txt | ./a.out 
bytes read: 6
program: hello

为什么 read() 只用第一行输入填充我的缓冲区?我在 man 3 read.

中看不到任何对换行符的引用

来自 linux 手册页 read(2) 手册:

RETURN VALUE

On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. On error, –1 is returned, and errno is set appropriately. In this case it is left unspecified whether the file position (if any) changes.

所以这是因为您正在从管道读取数据。显而易见的解决方案是继续阅读,直到返回 0