00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 #ifdef HAVE_CONFIG_H
00022 #include <config.h>
00023 #endif
00024
00025 #include <unistd.h>
00026 #include <inttypes.h>
00027 #include <string.h>
00028 #include <sys/types.h>
00029 #include <sys/wait.h>
00030
00031 #include "rwpipe.h"
00032
00033 RWPipe::RWPipe( ) : m_pid( -1 ), m_error( NULL )
00034 {}
00035
00036 RWPipe::~RWPipe( )
00037 {
00038 stop( );
00039 }
00040
00041 bool RWPipe::run( string command )
00042 {
00043 char * args[ 4 ];
00044
00045 args[ 0 ] = "/bin/sh";
00046 args[ 1 ] = "-c";
00047 args[ 2 ] = ( char * ) command.c_str( );
00048 args[ 3 ] = NULL;
00049
00050 return g_spawn_async_with_pipes( ".", args, NULL, G_SPAWN_LEAVE_DESCRIPTORS_OPEN, NULL, NULL, &m_pid, &m_writer, &m_reader, NULL, &m_error );
00051 }
00052
00053 bool RWPipe::isRunning( )
00054 {
00055 return m_pid != -1;
00056 }
00057
00058 int RWPipe::readData( void *data, int size )
00059 {
00060 if ( m_pid != -1 )
00061 {
00062 int bytes = 0;
00063 int len;
00064 uint8_t *p = ( uint8_t * ) data;
00065
00066 while ( size > 0 )
00067 {
00068 len = read( m_reader, p, size );
00069 if ( len <= 0 )
00070 break;
00071 p += len;
00072 size -= len;
00073 bytes += len;
00074 }
00075
00076 return bytes;
00077 }
00078 else
00079 return -1;
00080 }
00081
00082 int RWPipe::readLine( char *text, int max )
00083 {
00084 int len = -1;
00085 strcpy( text, "" );
00086 if ( m_pid != -1 )
00087 {
00088 while ( len < max - 1 && readData( &text[ ++ len ], 1 ) )
00089 if ( text[ len ] == '\n' )
00090 break;
00091 text[ len ] = '\0';
00092 }
00093 return len;
00094 }
00095
00096 int RWPipe::writeData( void *data, int size )
00097 {
00098 if ( m_pid != -1 )
00099 return write( m_writer, ( uint8_t * ) data, size );
00100 else
00101 return -1;
00102 }
00103
00104 void RWPipe::stop( )
00105 {
00106 if ( m_pid != -1 )
00107 {
00108 close( m_reader );
00109 close( m_writer );
00110 waitpid( m_pid, NULL, 0 );
00111 m_pid = -1;
00112 }
00113 }