tags:

views:

527

answers:

3

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.

+3  A: 

If you can use system pipes, simply pipe the other process's output to your C program, and in your C program, just read the standard input.

otherprocess | your_c_program
MiniQuark
this is of course useless if you want to process STDERR and STDOUT separately :)
Kent Fredric
not really you can use 2> and 1> to redirect STDERR and STDOUT to seperate files and then tail -f file | proc on each file to process each independently
hhafez
A: 

Which OS are you using? On *nix type OS if you are process is outputting to STDOUT or STDERR you can obviously use pipes

hhafez
+5  A: 

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.

Logan Capaldo
Thanks! It works great!
Geo