Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capture another process's output using C?

Tags:

c

capture

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.

like image 874
Geo Avatar asked Feb 28 '23 22:02

Geo


2 Answers

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.

like image 100
Logan Capaldo Avatar answered Mar 11 '23 08:03

Logan Capaldo


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
like image 29
MiniQuark Avatar answered Mar 11 '23 06:03

MiniQuark