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
popenshould work in most places, e.g.Note that this has a very specific use, it creates the process by running the command
acommandand attaches its standard out in a such as way as to make it accessible from your program through the streamFILE*.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
CreateProcessAPI to create a new process and hook up its standard output handle to what you want. Windows also supportspopen.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
popenseems 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.