[英]Is it possible to redirect stdout as stdin to same program?
I am writing a filter, and I am exploring an approach to write the program.我正在编写一个过滤器,并且我正在探索一种编写程序的方法。 I was wondering if this is possible: from input in stdin, write to stdout, but redirect this stdout such that the program reads the generated stdout as if it were stdin, again, thus re-processing the data.我想知道这是否可能:从标准输入中的输入写入标准输出,但重定向此标准输出,以便程序再次读取生成的标准输出,就好像它是标准输入一样,从而重新处理数据。 I do not wish to store the data in a gigantic array -- I wish to do this using streams, solely.我不希望将数据存储在一个巨大的数组中——我希望只使用流来做到这一点。 Is this even possible?这甚至可能吗? (if not, that's fine too.) Also, a note: I wish to do this only in a single source file of C code. (如果没有,那也没关系。)另外,请注意:我希望仅在 C 代码的单个源文件中执行此操作。
Yes, you can create a pipe to yourself in any POSIX system.是的,您可以在任何 POSIX 系统中为自己创建一个管道。
But "There ain't no such thing as a free lunch" .但是“天下没有免费的午餐” 。 If you need to store data, it has to go somewhere.如果你需要存储数据,它必须去某个地方。 The pipe is backed by a buffer managed by the OS.该管道由操作系统管理的缓冲区支持。
You can literally set the ends of the pipe to back stdin
and stdout
(as in Joachim's answer), but I'd advise against that, as it would override the usual input and output channels of the program.您可以从字面上将管道的末端设置为支持stdin
和stdout
(如 Joachim 的回答),但我建议不要这样做,因为它会覆盖程序的通常输入和输出通道。 (Neither C nor any POSIX service will "tee" the stream so the user can see it as well as have it echoed inside the program.) (C 和任何 POSIX 服务都不会“发送”流,以便用户可以看到它并在程序中回显它。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.