How can I capture the output of another process using C?

advertisements

How can I capture another process's output using pure C? Can you provide sample code?

EDIT: let's assume Linux. I would be interested in "pretty portable" code. All I want to do is to execute a command, capture it's output and process it in some way.


There are several options, but it does somewhat depend on your platform. That said popen should work in most places, e.g.

#include <stdio.h>

FILE *stream;
stream = popen("acommand", "r");

/* use fread, fgets, etc. on stream */

pclose(stream);

Note that this has a very specific use, it creates the process by running the command acommand and attaches its standard out in a such as way as to make it accessible from your program through the stream FILE*.

If you need to connect to an existing process, or need to do richer operations, you may need to look into other facilities. Unix has various mechanisms for hooking up a processes stdout etc.

Under windows you can use the CreateProcess API to create a new process and hook up its standard output handle to what you want. Windows also supports popen.

There's no plain C way to do this that I know of though, so it's always going somewhat dependent on platform specific APis.

Based on your edits popen seems ideal, it is "pretty portable", I don't think there's a unix like OS without it, indeed it is part of the Single Unix Specification, and POSIX, and it lets you do exactly what you want, execute a process, grab its output and process it.