views:

352

answers:

4

I want to execute a sub-process in C++. I need it to work on Windows and Linux. Is there such a function in Boost? What is the standard way of doing it?

A: 

ANSI C89 system() exists on both platforms. Obviously what that process does depends on whether it works portably between platforms. But you certainly don't need boost to do it.

Andy Ross
system() just forwards a command to the underlying shell. It does not allow you to read the stdout stream, or send data to the stdin stream.
StackedCrooked
The question doesn't ask for stdio redirection, though. Nor do external tools between these platforms normally do so portably anyway.
Andy Ross
If you need to use system(), and want to redirect stdout or stderr, just pipe all the data into a text file and read it off later.
blwy10
+1  A: 

What level of control do you want? The standard includes system(), which can execute a sub-process. If you want to control standard input or standard output, you can use popen (though MS usually calls it _popen). You only really need to look elsewhere if you want something more elaborate than that.

Jerry Coffin
+1  A: 

There is the not-yet-approved Boost.Process library. I never tried it, but it may do the job for you.

I've professionally and successfully used Poco's Process API though.

StackedCrooked
+2  A: 

Poco and ACE have Process classes that do what you want. See Foundation->Processes->Process in Poco; Process.h/Process.cpp for Ace. I wouldn't be surprised if QT has something similar.

As for how to do it, basically you wrap the OS dependencies and bury the details. Poco and Ace offer contrasting common methods. Poco tends to handle things by writing implementation objects (xxx_impl) for each platform with the proper one getting pulled in depending on the OS. ACE seems to #ifdef the code, sometimes to the point of madness, though in fairness it has been a long time since I looked at that code.

Duck