Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ best way to launch another process?

Tags:

c++

fork

spawn

Its been a while since I've had to do this and in the past I've used "spawn" to create processes.

Now I want to launch processes from my application asynchronously so my application continues to execute in the background and does not get held up by launching the process.

I also want to be able to communicate with the launched processes. When I launch the process I will send it the launchers process id so that the launched process can communicate with the launcher using it's pid.

What is the best method to use that is not specific to any platform / operating system, I'm looking for a solution that is multi-platform?

I'm writing this in C++, I don't want a solution that ties me to any third party licensed product.

I don't want to use threads, the solution must be for creating new processes.

like image 204
SPlatten Avatar asked Oct 27 '22 16:10

SPlatten


1 Answers

Try Boost.Process.

Boost.Process provides a flexible framework for the C++ programming language to manage running programs, also known as processes. It empowers C++ developers to do what Java developers can do with java.lang.Runtime/java.lang.Process and .NET developers can do with System.Diagnostics.Process. Among other functionality, this includes the ability to manage the execution context of the currently running process, the ability to spawn new child processes, and a way to communicate with them them using standard C++ streams and asynchronous I/O.

The library is designed in a way to transparently abstract all process management details to the user, allowing for painless development of cross-platform applications. However, as such abstractions often restrict what the developer can do, the framework allows direct access to operating system specific functionality - obviously losing the portability features of the library.

Example code to run and wait to finish for child process from the site:

bp::child c(bp::search_path("g++"), "main.cpp");

while (c.running())
    do_some_stuff();

c.wait(); //wait for the process to exit   
int result = c.exit_code();
like image 53
Oliort UA Avatar answered Nov 12 '22 21:11

Oliort UA