[英]How do I read from a pipe when not knowing how much data will be sent through the pipe?
我试图通过管道将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调用。
您需要在管道的两端之间开发协议,以使您能够在管道的两端之间发送“ SET_BUFF_SIZE”消息。 或使用带有消息字符串的开头和结尾的固定大小的缓冲区,这将使您能够根据需要将数据“分块”为多个读取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.