Subprocesses, the Console, and Storing Output

I was doing some Python when I came up with the sudden urge to write something that stores the output I get in the console. I though "well, how do I store the lines from something like 'netstat' in a buffer?" Naturally, I thought it'd be too hard to do it in Python because I'm more comfortable with C, so I looked up some stuff on subprocesses in C. I just used the popen() manpages for this, really. I modified the code there to do what I want. This might be considered sloppy, but whatever! This is a really small PoC in C:

/*  
*
* Writing netstat to a file
* Greg Thompson Jr.
*
*
*/
#include <stdio.h>
#include <stdlib.h>

void write_netstat(FILE * stream)  
{
          FILE * outfile;
          outfile = fopen("output.txt","w");
          char line[128];

          if(!ferror(stream))
          {
                    while(fgets(line, sizeof(line), stream) != NULL)
                    {
                              fputs(line, outfile);
                              printf("%s", line);
                    }
                    fclose(outfile);
          }
          else
          {
                    fprintf(stderr, "Output to stream failed.n");
                    exit(EXIT_FAILURE);
          }
}

int main(void)  
{
          FILE * output;
          output = popen("netstat", "r");

          if(!output)
          {
                    fprintf(stderr, "incorrect params or too many files.n");
                    return EXIT_FAILURE;
          }

          write_netstat(output);

          if(pclose(output) != 0)
          {
                    fprintf(stderr, "Could not run 'netstat' or other error.n");
          }
          return EXIT_SUCCESS;
}

I think I'll do the same thing in Python soon just to see how different the code is from this. By the way, I'm reading "Web Programming with Django." I'm impressed. I'll let you guys know how it is when I'm done with it. So far: simple, very nice.  Though, I might stop reading it and switch to something a little shorter with better reviews.

Greg

Software Engineer

Subscribe to GregBlogs