tags:

views:

3875

answers:

6

I'm trying to start an external application through system() - for example system("ls") - i would like to capture it's output as it happens so i can send it to another function for further processing. What's the best way to do that in C/C++ ?

A: 

I'm not entirely certain that its possible in standard C, as two different processes don't typically share memory space. The simplest way I can think of to do it would be to have the second program redirect its output to a text file (programname > textfile.txt) and then read that text file back in for processing. However, that may not be the best way.

Nicholas Flynt
+3  A: 

EDIT: misread question as wanting to pass output to another program, not another function. popen() is almost certainly what you want.

System gives you full access to the shell. If you want to continue using it, you can redirect it's output to a temporary file, by system("ls > tempfile.txt"), but choosing a secure temporary file is a pain. Or, you can even redirect it through another program: system("ls | otherprogram");

Some may recommend the popen() command. This is what you want if you can process the output yourself:

FILE *output = popen("ls", "r");

which will give you a FILE pointer you can read from with the command's output on it.

You can also use the pipe() call to create a connection in combination with fork() to create new processes, dup2() to change the standard input and output of them, exec() to run the new programs, and wait() in the main program to wait for them. This is just setting up the pipeline much like the shell would. See the pipe() man page for details and an example.

wnoise
popen() returns a FILE pointer, not a integer file descriptor.
jkramer
A: 

In windows, instead of using system(), use CreateProcess, redirect the output to a pipe and connect to the pipe.

I'm guessing this is also possible in some posix way?

shoosh
+8  A: 

From the popen manual:

#include <stdio.h>

FILE *popen(const char *command, const char *type);

int pclose(FILE *stream);
jkramer
+2  A: 

Try the popen() function. It executes a command, like system(), but directs the output into a new file. A pointer to the stream is returned.

FILE *lsofFile_p = popen("lsof", "r");

if (!lsofFile_p) { return -1; }

char buffer[1024]; char *line_p = fgets(buffer, sizeof(buffer), lsofFile_p); pclose(lsofFile_p);

A: 

The functions popen() and pclose() could be what you're looking for.

Take a look at the glibc manual for an example.

Andrew Edgecombe