所以我尝试用 Boost.Process 做点什么尽管它还没有被接受到 Boost 发行版中。
最简单的程序看起来像
#include <boost/process.hpp>
#include <string>
#include <vector>
namespace bp = ::boost::process;
void Hello()
{
//... contents does not matter for me now - I just want to make a new process running this function using Boost.Process.
}
bp::child start_child()
{
std::string exec = "bjam";
std::vector<std::string> args;
args.push_back("--version");
bp::context ctx;
ctx.stdout_behavior = bp::silence_stream();
return bp::launch(exec, args, ctx);
}
int main()
{
bp::child c = start_child();
bp::status s = c.wait();
return s.exited() ? s.exit_status() : EXIT_FAILURE;
}
我创建的 tall 进程如何执行 Hello() 函数?
最佳答案
你不能。另一个进程是另一个可执行文件。除非您生成同一程序的另一个实例,否则子进程甚至不会包含 Hello() 函数。
如果 child 是您程序的另一个实例,您需要定义自己的方式来告诉 child 运行 Hello()。这可能是进程参数或 std:cin 上的一些协议(protocol)(即使用标准输入进行进程间通信)
在 UNIX/Linux 平台上,您可以启动另一个进程而不是运行不同的可执行文件。请参阅 fork(2) 系统调用。然后你可以在 child 中调用 Hello() 。但是 boost::process:launch(9 在这样的平台上映射到 fork+exec。普通的 fork() 不会被 boost 暴露,例如因为它在其他平台上不存在。
可能有非常依赖于平台的方法来做你想做的事,但你不想去那里。
关于c++ - Boost.Process - 如何让一个进程运行一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4774932/