Boost.Process - 如何使进程运行一个函数?

Rel*_*lla 3 c++ boost function process interprocess

所以我尝试用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; 
} 
Run Code Online (Sandbox Code Playgroud)

如何高进程我正在创建执行Hello()函数?

Joe*_*rgB 7

你不能.另一个过程是另一个可执行 除非您生成同一程序的另一个实例,否则子进程甚至不包含Hello()函数.

如果孩子是你的程序的另一个实例,你需要定义自己的方式告诉孩子运行Hello().这可能是进程参数或std:cin上的某些协议(即使用标准输入进行进程间通信)

在UNIX/Linux平台上,您可以启动另一个进程,而不是运行不同的可执行文件.请参阅fork(2)系统调用.然后你可以在孩子中调用Hello().但是boost :: process:launch(9在这样的平台上映射到fork + exec.普通的fork()不会被boost暴露,例如因为它在其他平台上不存在.

可能有非常依赖于平台的方式来做你想要的,但你不想去那里.