Spawn a program/console command and retrieve its stdout/stderr output

banders7 0 Tallied Votes 214 Views Share

This a routine that executes a _popen() pipe on your behalf and retrieves the spawned program's/comand's console output for you. Useful if your program needs data from another program and can't communicate directly with it.

#if !defined(__RUNPIPE_I) // Preclude multiple includes causing problems
#define __RUNPIPE_I       // If included/defined elsewhere, 2nd+ copies ignored
#include <stdio.h>        // for _popen()/_pclose()
// Spawn another program/command and retrieve its console output
// _popen() is essentially a system() command that returns the cousole output
// Make sure buffer is a decent size. 1024 or more is not unreasonable
// How big depends on how much data you expect back
int runpipe(char program[],char parms[],char buffer[],int bufsize);
int runpipe(char program[],char parms[],char buffer[],int bufsize)
{
int i,j,k;
char command[200]; // Overkill, but storage is cheap
FILE *pipe;
char inchar;

// _popen() does not normally capture STDERR output, just STDOUT
// Redirect STDERR to STDOUT with 2>&1
// Up to caller to determine contents of buffer - Valid output or stderr

// An as-I-post-this observation:
// No real need for distinction between program and parms ...
// A carryover from this routine's original spawnlp implementation
sprintf(command,"%s %s 2>&1",program,parms);
pipe = _popen(command,"rt");
if (pipe == NULL)
   {
   sprintf(buffer,"Error establishing pipe. Command: %s\n",command);
   k = strlen(buffer) * -1;
   return k;
   }

// Do a byte read of the file ... some output contains binary 0s.
// e.g. "fsutil fsinfo drives" returns output with embedded binary 0s.
// A string read only picks up data to that point
// Note: You may need to scan buffer and replace 0x0s with ' 's (0x32)
inchar = fgetc(pipe);
i = 0;
// Keep an eye on how much room left in the supplied buffer
// Make sure not to overrun the end of it
while(!feof(pipe) && i<bufsize && inchar != 0xffffffff)
   {
   buffer[i] = inchar;
   i++;
   inchar = fgetc(pipe);
   }
buffer[i] = '\0'; // Insert string terminator.
_pclose(pipe);
// What to do if out of buffer space(i==bufsize)? Zap buffer, insert message?
// Let user figure it out? Insert Executive Decision here
// Return length of data in buffer
return i;
}
#endif
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.