1 /* Pipestream: A simple C++ interface to UNIX pipes 2 Version 0.05 3 Copyright (C) 2005-2014 John C. Bowman, 4 with contributions from Mojca Miklavec 5 6 This program is free software; you can redistribute it and/or modify 7 it under the terms of the GNU Lesser General Public License as published by 8 the Free Software Foundation; either version 3 of the License, or 9 (at your option) any later version. 10 11 This program is distributed in the hope that it will be useful, 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU Lesser General Public License for more details. 15 16 You should have received a copy of the GNU Lesser General Public License 17 along with this program; if not, write to the Free Software 18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ 19 20 #ifndef PIPESTREAM_H 21 #define PIPESTREAM_H 22 23 #include <sys/wait.h> 24 #include <unistd.h> 25 #include <fcntl.h> 26 27 #include "common.h" 28 29 // bidirectional stream for reading and writing to pipes 30 class iopipestream { 31 protected: 32 int in[2]; 33 int out[2]; 34 static const int BUFSIZE=SHRT_MAX; 35 char buffer[BUFSIZE]; 36 string sbuffer; 37 int pid; 38 bool Running; 39 bool pipeopen; 40 bool pipein; 41 public: 42 43 void open(const mem::vector<string> &command, const char *hint=NULL, 44 const char *application="", int out_fileno=STDOUT_FILENO); 45 isopen()46 bool isopen() {return pipeopen;} 47 iopipestream()48 iopipestream(): pid(0), pipeopen(false) {} 49 50 iopipestream(const mem::vector<string> &command, const char *hint=NULL, 51 const char *application="", int out_fileno=STDOUT_FILENO) : 52 pid(0), pipeopen(false) { 53 open(command,hint,application,out_fileno); 54 } 55 56 void eof(); 57 virtual void pipeclose(); 58 ~iopipestream()59 virtual ~iopipestream() { 60 pipeclose(); 61 } 62 63 void block(bool write=false, bool read=true); 64 65 ssize_t readbuffer(); 66 string readline(); 67 running()68 bool running() {return Running;} 69 70 typedef iopipestream& (*imanip)(iopipestream&); 71 72 iopipestream& operator << (imanip func) { 73 return (*func)(*this); 74 } 75 76 iopipestream& operator >> (string& s) { 77 readbuffer(); 78 s=buffer; 79 return *this; 80 } 81 82 bool tailequals(const char *buf, size_t len, const char *prompt, 83 size_t plen); 84 getbuffer()85 string getbuffer() {return sbuffer;} 86 87 void wait(const char *prompt); 88 int wait(); 89 void Write(const string &s); 90 91 iopipestream& operator << (const string& s) { 92 Write(s); 93 return *this; 94 } 95 96 template<class T> 97 iopipestream& operator << (T x) { 98 ostringstream os; 99 os << x; 100 Write(os.str()); 101 return *this; 102 } 103 }; 104 105 #endif 106