Boost :: process - 如何让它只运行一个进程?

时间:2011-09-15 21:47:47

标签: c++ boost process multiprocessing

因此,使用boost :: process(我从最新的boost sandbox svn获取),我们可以执行诸如启动一个应用程序并将输出重定向到这样的代码的文件:

#include <string> 
#include <vector> 
#include <iostream> 
#include <algorithm>
#include <iterator>
#include <boost/asio.hpp>
#include <boost/process.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>  

std::vector<std::string> split(const std::string& s, const std::string& delim, const bool keep_empty = false) {
    std::vector<std::string> result;
    if (delim.empty()) {
        result.push_back(s);
        return result;
    }
    std::string::const_iterator substart = s.begin(), subend;
    while (true) {
        subend = search(substart, s.end(), delim.begin(), delim.end());
        std::string temp(substart, subend);
        if (keep_empty || !temp.empty()) {
            result.push_back(temp);
        }
        if (subend == s.end()) {
            break;
        }
        substart = subend + delim.size();
    }
    return result;
}

 boost::process::child start_child(boost::filesystem::path path_to_exec, std::string arguments) 
{ 

    std::string exec = path_to_exec.string();
    boost::process::context ctx; 
    ctx.environment = boost::process::self::get_environment();
    ctx.stdout_behavior =  boost::process::capture_stream(); 

    #if defined(BOOST_POSIX_API) 
        return  boost::process::launch(exec, split(arguments, " "), ctx); 
    #elif defined(BOOST_WINDOWS_API)
        return  boost::process::launch_shell(exec + " " + arguments, ctx); 
    #else 
    #  error "Unsupported platform." 
    #endif 
} 


int main() 
{ 
    boost::filesystem::path exec =  boost::filesystem::current_path();
    exec /= "CloudClient/CloudClient.exe";
     boost::process::child c = start_child(exec, "--server=127.0.0.1:4773/ --username=robota --robot > file.a"); 
     boost::process::pistream &is = c.get_stdout();
     std::string line; 
     while (std::getline(is, line)) 
         std::cout << line << std::endl; 

     boost::process::status s = c.wait(); 
     std::cin.get();
} 

但是我想限制它,以便它只启动一个进程 - 在应用程序中,并且无法创建这样的管道。是否有可能使我的boost::process::child start_child(boost::filesystem::path path_to_exec, std::string arguments)功能安全或至少更安全地关注我想要的东西?


顺便说一句:在Windows上我不能使用return boost::process::launch(exec, split(arguments, " "), ctx);而不是我试图开始破碎的应用程序=(

1 个答案:

答案 0 :(得分:0)

也许如下。

bp::context ctx;
ctx.stdout_behavior = bp::silence_stream();
bp::launch(exec, args, ctx);