Question

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.

Was it helpful?

Solution

Yes, you can create a pipe to yourself in any POSIX system.

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. (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.)

OTHER TIPS

Create a pipe. Duplicate the read-end of the pipe as the new STDIN_FILENO, the write-end as STDOUT_FILENO, and you're all set. Everything you now write to stdout will be available on stdin.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top