c - 当不知道将通过管道发送多少数据时,如何从管道中读取数据?

标签 c shell pipe exec

我试图通过管道传递 excev 调用的输出,读取它,然后对其进行另一个 execv 调用。例如,ls -l |更多的。我不确定如何读取通过管道传输的数据。我试图找到一个关于如何使用其他资源执行此操作的好答案,但所有资源都使用带有固定大小字符串的非常基本的示例。我是否需要动态读取数据以允许或多或少,或者它可以是固定大小的缓冲区?

else {
    int pipefd[2];
    pipe(pipefd);

    int rc = fork();
    if(rc == -1) {
       error();
    }
    if (rc == 0) {

    // close reading end in the child
    close(pipefd[0]);

    // send stdout to the pipe
    if(dup2(pipefd[1], 1) == -1) {
            error();
    }

    // send stderr to the pipe
    if(dup2(pipefd[1], 2) == -1) {
            error();
    }

    // this descriptor is no longer needed
            close(pipefd[1]);

    // example 
    // path: /bin/ls
    // commands: ls -l
    if (access(path, X_OK) == 0) {
           execv(path, commands);
           error();
    }
           free(path);
           exit(1);
 }

} else {
    // parent process
    wait(NULL);
    // close the write end of the pipe in the parent
    close(pipefd[1]);
    // do I read here?


 }

预期结果是从管道中读取它们,然后对该数据执行另一个 execv 调用。

最佳答案

您需要在管道两端之间开发一个协议(protocol),使您能够在管道两端之间发送“SET_BUFF_SIZE”消息。 或者 使用固定大小的缓冲区以及消息字符串的开头和结尾,这将使您能够根据需要将数据“分块”为多次读取。

关于c - 当不知道将通过管道发送多少数据时,如何从管道中读取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54704825/

相关文章:

java - 如何制定图像压缩算法?

c - 与具有超过 500 万个键值对的 REDIS 匹配的最长前缀

linux - 如何在变量中传递值

python - 使用 bash 脚本将文件中的各个行传递到 python 脚本中

java - 如何使用java读取linux中的命名管道(FIFO)

Haskell:System.Process 合并标准输出和标准错误

c - 如何在 C 文件中通过 F12 或 Ctrl-Shift-O 使用 JUMP 功能?

c - 连接字符串和数字的最佳方式是什么 - 使用 C 的性能?

linux - 在bash附加换行符中连接两个字符串变量

在父进程和子进程之间创建管道