#include <stdio.h>
#include <unistd.h>
#include <stdhdrs.h>
#include <strbuf.h>
#include <error.h>
#include <errorlog.h>
#include <options.h>
#include "log.h"
#include "usage.h"
#include "msgcpipe.h"
#include "spawn.h"
#include "pipe.h"
#include "err.h"
#define BUFSIZE 32768
bool ParseArgs( int *argc, char ***argv, Options *options, Error *e )
{
(*argc)--;
(*argv)++;
options->Parse( *argc, *argv, "h?V", OPT_ANY,
MsgCpipe::ShortUsage, e );
if( e->Test() )
return false;
return true;
}
bool ReadStdin( char *buf, size_t count, ssize_t *n, Error *e )
{
if( ( *n = read( 0, buf, count ) ) == -1 )
return syserr( "read", "stdin", e );
return true;
}
bool Init( int argc, char **argv, Pipe *pipe, Spawn *spawn, Error *e )
{
if( !pipe->Init( "cpipe", e ) )
return false;
if( !spawn->Init( argc, argv, e ) )
return false;
return true;
}
bool Run( char *buf, ssize_t *n, Pipe *pipe, Spawn *spawn, Error *e )
{
if( !pipe->Open( e ) )
return false;
if( !spawn->Exec( pipe->GetIfd(), e ) )
return false;
do
{
if( !pipe->Write( buf, *n, e ) )
return false;
if( !ReadStdin( buf, BUFSIZE, n, e ) )
return false;
}
while( *n );
if( !pipe->Close( e ) )
return false;
if( !spawn->Wait( e ) )
return false;
return true;
}
int Final( Error *e )
{
return true;
}
int main( int argc, char **argv );
int main( int argc, char **argv )
{
Options options;
char buf[ BUFSIZE ];
ssize_t n;
Pipe pipe;
Spawn spawn;
Error e;
if( !ParseArgs( &argc, &argv, &options, &e ) )
return printerr( &e );
if( options[ 'h' ] || options[ '?' ] )
{
LongUsage();
return 0;
}
if( options[ 'V' ] )
{
printf( "cpipe Version 0.77 (beta)\n" );
return 0;
}
if( !ReadStdin( buf, BUFSIZE, &n, &e ) )
return printerr( &e );
if( !n )
return 0;
if( !Init( argc, argv, &pipe, &spawn, &e ) )
return printerr( &e );
if( !Run( buf, &n, &pipe, &spawn, &e ) )
return printerr( &e );
if( !Final( &e ) )
return printerr( &e );
return 0;
}