00001
00002
00003
00004 #ifndef _SystemCmd_h
00005 #define _SystemCmd_h
00006
00007 #include <sys/poll.h>
00008 #include <stdio.h>
00009
00010 #include <string>
00011 #include <vector>
00012
00013 using std::string;
00014
00015 class OutputProcessor;
00016
00017 class SystemCmd
00018 {
00019 public:
00020 enum OutputStream { IDX_STDOUT, IDX_STDERR };
00021 SystemCmd( const char* Command_Cv );
00022 SystemCmd( const string& Command_Cv );
00023 SystemCmd();
00024 virtual ~SystemCmd();
00025 int execute( const string& Command_Cv );
00026 int executeBackground( const string& Command_Cv );
00027 void setOutputHandler( void (*Handle_f)( void *, string, bool ),
00028 void * Par_p );
00029 void logOutput();
00030 void setOutputProcessor( OutputProcessor * proc )
00031 { output_proc = proc; }
00032 int select( string Reg_Cv, bool Invert_bv=false,
00033 unsigned Idx_ii=IDX_STDOUT );
00034 const string& stderr() const { return( *getString(IDX_STDERR)); }
00035 const string& stdout() const { return( *getString(IDX_STDOUT)); }
00036 const string& cmd() const { return( lastCmd ); }
00037 const string* getString( unsigned Idx_ii=IDX_STDOUT ) const;
00038 const string* getLine( unsigned Num_iv, bool Selected_bv=false,
00039 unsigned Idx_ii=IDX_STDOUT ) const;
00040 unsigned numLines( bool Selected_bv=false, unsigned Idx_ii=IDX_STDOUT ) const;
00041 void setCombine( const bool Combine_b=true );
00042 int retcode() const { return Ret_i; }
00043
00044 int getStdout( std::vector<string> &Ret_Cr, const bool Append_bv = false ) const
00045 { return placeOutput( IDX_STDOUT, Ret_Cr, Append_bv); }
00046 int getStderr( std::vector<string> &Ret_Cr, const bool Append_bv = false ) const
00047 { return placeOutput( IDX_STDERR, Ret_Cr, Append_bv); }
00048
00049 protected:
00050
00051 int placeOutput( unsigned Which_iv, std::vector<string> &Ret_Cr, const bool Append_bv ) const;
00052
00053 void invalidate();
00054 void closeOpenFds();
00055 int doExecute( string Cmd_Cv );
00056 bool doWait( bool Hang_bv, int& Ret_ir );
00057 void checkOutput();
00058 void getUntilEOF( FILE* File_Cr, std::vector<string>& Lines_Cr,
00059 bool& NewLineSeen_br, bool Stderr_bv );
00060 void extractNewline( const char* Buf_ti, int Cnt_ii, bool& NewLineSeen_br,
00061 string& Text_Cr, std::vector<string>& Lines_Cr );
00062 void addLine( string Text_Cv, std::vector<string>& Lines_Cr );
00063 void init();
00064
00065 mutable string Text_aC[2];
00066 mutable bool Valid_ab[2];
00067 FILE* File_aC[2];
00068 std::vector<string> Lines_aC[2];
00069 std::vector<string*> SelLines_aC[2];
00070 bool NewLineSeen_ab[2];
00071 bool Combine_b;
00072 bool Background_b;
00073 string lastCmd;
00074 int Ret_i;
00075 int Pid_i;
00076 void (* OutputHandler_f)( void*, string, bool );
00077 void *HandlerPar_p;
00078 OutputProcessor* output_proc;
00079 struct pollfd pfds[2];
00080 static int Nr_i;
00081 };
00082
00083 #endif