C++ 启动另一个进程的最佳方式?

标签 c++ fork spawn

自从我不得不这样做以来已经有一段时间了,过去我使用“spawn”来创建进程。

现在我想从我的应用程序异步启动进程,以便我的应用程序继续在后台执行并且不会因启动进程而受阻。

我还希望能够与启动的进程进行通信。当我启动进程时,我会向它发送启动器进程 ID,以便启动的进程可以使用它的 pid 与启动器通信。

不特定于任何平台/操作系统的最佳使用方法是什么,我正在寻找一个多平台的解决方案?

我正在用 C++ 编写此代码,我不想要将我与任何第三方许可产品联系在一起的解决方案。

我不想使用线程,解决方案必须是创建新进程。

最佳答案

尝试 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.

运行并等待站点子进程完成的示例代码:

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();

关于C++ 启动另一个进程的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55490271/

相关文章:

r - 如何为多核处理重写我的 R 代码?

c++ - 当每个数据都是不同的类型和逗号分隔符时,从文件输入数据

c++ - 在 C++ 中使用指针加速访问数组

c - 无法在C中的父进程和子进程之间发送信号

windows - 对于 ruby​​/webrick,我需要 Windows 来识别 shebang (#!) 符号

ruby - 意外的 ruby​​ 全局数组变量行为

java - 如何获取生成的 Java 进程的 PID

node.js - 允许 powershell 控制台在 NodeJS 中显示

c++ - 如何处理太长的 STL 模板错误报告?

c++ - 在 C++ 中实现 'bounded genericity'