#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/utsname.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include "HelperRoutines.h"
#include "CommandLine.h"
namespace out_of_band_example
{
static const int MAX_LINE_LENGTH = 4096;
void
FeedFileToSubprogram( const std::string& aFileName,
const std::string& aSubprogramPath,
const tools::CommandLine& commands )
{
// Open the input file and pipe the contents to the child
// program:
FILE * fdInput = fopen( aFileName.c_str(), "r");
if( fdInput < 0 )
{
std::cout << "Failed to open the input file: " << aFileName
<< std::endl;
exit(1);
}
// Launch the child program:
FILE * fdChildProgram;
if ( (fdChildProgram = popen( aSubprogramPath.c_str(), "w")) < 0 )
{
std::cout << "Failed to launch program " << aSubprogramPath
<< std::endl;
exit(2);
}
if( commands.Exists("version") )
{
pclose( fdChildProgram );
exit(0);
}
// Pipe contents of the input file to the child program's
// standard input:
int bytesRead = 0;
char buffer [ MAX_LINE_LENGTH ];
memset(buffer, 0, sizeof(buffer));
while( fgets(buffer, MAX_LINE_LENGTH, fdInput ) != NULL)
{
if( fputs( buffer, fdChildProgram) == EOF )
{
std::cout << "Error writing to the child process."
<< std::endl;
exit(3);
}
}
if( ferror( fdInput) )
{ std::cout << "Error reading from the file: " << aFileName
<< std::endl;
}
fclose( fdInput );
if( -1 == pclose( fdChildProgram ) )
{
std::cout << "Error closing the pipe to the child process: " <<
aSubprogramPath << std::endl;
exit(4);
}
}
std::string
GetEnv(const std::string& variableName)
{
std::string strValue;
char* pValue = getenv( variableName.c_str() );
if( pValue )
{ strValue = pValue;
}
return strValue;
}
std::string
CombinePathAndFile( const std::string& aPath,
const std::string& aFileName)
{
if( aPath[aPath.length() - 1] == '/' )
{ return (aPath + aFileName);
}
return aPath + "/" + aFileName;
}
} // end of the out_of_band_example namespace
End of Listing