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

问题描述 投票:0回答:1

所以我尝试用 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() 函数?

c++ function boost process interprocess
1个回答
8
投票

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.