从 STDIN 读取和写入超过 4096 个字节

问题描述 投票:0回答:1

我正在尝试实现一个类似于 bash (在 C 中)中使用的文档,但我注意到我不能给它超过 4096 字节的行,我查了一下,这是因为 max内核 I/O 队列的大小,因此我的进程永远不会收到我在 shell 中键入的完整输入。同时 bash 的heredoc 可以处理这个问题。有没有办法使用 C 来解决这个问题。

对于超过 4096 个字符的任何单词,仅打印 4096 个字符,否则输入会损坏

#include <unistd.h>

int main()
{
    ssize_t r_bytes;
    char buf[42];
    while (r_bytes = read(0, buf, 42))
    {
        write(1, buf, r_bytes);
    }
    return (0);
}
c linux bash shell stdin
1个回答
0
投票

要在 C 中处理长度超过 4096 字节的输入行,您可以将终端切换到 Non-Canonical 模式(也称为 Raw 模式)。

在非规范模式下,输入立即可用,无需等待换行符,允许您处理超出典型缓冲区大小的输入。

查看您按上述方式修改的代码:

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

void setRawMode(int fd) {
    struct termios term;
    tcgetattr(fd, &term);
    term.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(fd, TCSANOW, &term);
}

void setCanonicalMode(int fd) {
    struct termios term;
    tcgetattr(fd, &term);
    term.c_lflag |= (ICANON | ECHO);
    tcsetattr(fd, TCSANOW, &term);
}

int main() {
    setRawMode(STDIN_FILENO);

    ssize_t r_bytes;
    char buf[42];
    while ((r_bytes = read(STDIN_FILENO, buf, sizeof(buf) - 1)) > 0) {
        buf[r_bytes] = '\0'; 
        printf("%s", buf);
    }

    setCanonicalMode(STDIN_FILENO);

    return 0;
}

© www.soinside.com 2019 - 2024. All rights reserved.