gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:49:16 28 4
gpt4 key购买 nike

自从我不得不这样做以来已经有一段时间了,过去我使用“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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com