From 5b541316a8c7bbf8b812c0f1e2dbebaa6563b0ee Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Wed, 30 May 2012 19:00:56 +0000 Subject: [PATCH] Add functions to support console redirection --- source/io/base.cpp | 5 +++++ source/io/base.h | 5 +++++ source/io/console.cpp | 11 +++++++++++ source/io/console.h | 5 +++++ 4 files changed, 26 insertions(+) diff --git a/source/io/base.cpp b/source/io/base.cpp index bf4c820..052d464 100644 --- a/source/io/base.cpp +++ b/source/io/base.cpp @@ -57,5 +57,10 @@ void Base::set_eof() } } +const Handle &Base::get_handle(Mode) +{ + throw logic_error("Base::get_handle"); +} + } // namespace IO } // namespace Msp diff --git a/source/io/base.h b/source/io/base.h index 61819cf..3d86216 100644 --- a/source/io/base.h +++ b/source/io/base.h @@ -2,6 +2,7 @@ #define MSP_IO_BASE_H_ #include +#include "handle.h" #include "mode.h" #include "poll.h" @@ -88,6 +89,10 @@ protected: public: /** Returns the end-of-file flag. */ bool eof() const { return eof_flag; } + + /** Returns the system-level handle for the object. Used by Console to + perform redirections. */ + virtual const Handle &get_handle(Mode); }; } // namespace IO diff --git a/source/io/console.cpp b/source/io/console.cpp index d06b894..259f80f 100644 --- a/source/io/console.cpp +++ b/source/io/console.cpp @@ -1,5 +1,6 @@ #ifndef WIN32 #include +#include #include #include #include @@ -125,6 +126,16 @@ void Console::get_size(unsigned &rows, unsigned &cols) #endif } +void Console::redirect(Base &other) +{ + Handle other_handle = other.get_handle(mode&M_RDWR); +#ifdef WIN32 + SetStdHandle(stream_to_sys(stream), *other_handle); +#else + dup2(*other_handle, *handle); +#endif +} + unsigned Console::do_write(const char *buf, unsigned len) { check_access(M_WRITE); diff --git a/source/io/console.h b/source/io/console.h index 5b4158f..d29ef00 100644 --- a/source/io/console.h +++ b/source/io/console.h @@ -46,6 +46,11 @@ public: Console. */ void get_size(unsigned &rows, unsigned &cols); + /** Redirects input from or output to another I/O object. This performs a + system-level redirect. Closing the other object won't affect the + redirection. */ + void redirect(Base &); + protected: virtual unsigned do_write(const char *, unsigned); virtual unsigned do_read(char *, unsigned); -- 2.43.0