c++ 如何用Boost.Process 0.5运行命令行/终端工具?

6fe3ivhb  于 2023-02-20  发布在  其他
关注(0)|答案(1)|浏览(152)

我发现有一个新的Boost.Process 0.5,但我不知道如何执行跨Windows Linux和Mac pingecho
我得到了它的工作至少在Windows上与简单:

#include <string>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/process.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/system/error_code.hpp>

namespace bp = boost::process;
namespace bpi = boost::process::initializers;
namespace bio = boost::iostreams;
int main()
{
    bp::pipe p = bp::create_pipe();
    {
        bio::file_descriptor_sink sink(p.sink, bio::close_handle);
        boost::filesystem::path p("C:/Windows/System32/cmd.exe");
        boost::system::error_code ec;
        bp::execute(
            bpi::run_exe(p),
            bpi::set_cmd_line(L"cmd /c echo --echo-stderr hello"),
            bpi::bind_stdout(sink),
            bpi::set_on_error(ec)
            );
    }

    bio::file_descriptor_source source(p.source, bio::close_handle);
    bio::stream<bio::file_descriptor_source> is(source);

    std::string s;
    is >> s;
    std::cout << s << std::endl;
    std::cin.get();
    return 0;
}

在Windows上,这可以正常工作,但如何使它跨平台工作,也在Mac和Linux上?(我很愚蠢,不知道如何写一个路径,将工作的任何Unix终端(或至少为Linux的Bash和Mac默认之一))所以如何运行命令行/终端工具与Boost.Process 0. 5在Windows和Unix一样的操作系统(最好不要每次都写终端的路径,而只写echoping之类的应用程序及其参数)?
...在Preveus版本中找到相关代码:

std::string exe; 
    std::vector<std::string> args; 

#if defined(BOOST_POSIX_API) 
    exe = "/bin/sh"; 
    args.push_back("sh"); 
    args.push_back("-c"); 
    args.push_back(command); 
#elif defined(BOOST_WINDOWS_API) 
    char sysdir[MAX_PATH]; 
    UINT size = ::GetSystemDirectoryA(sysdir, sizeof(sysdir)); 
    if (!size) 
        boost::throw_exception(boost::system::system_error(boost::system::error_code(::GetLastError(), boost::system::get_system_category()), "boost::process::launch_shell: GetWindowsDirectory failed")); 
    BOOST_ASSERT(size < MAX_PATH); 

    exe = std::string(sysdir) + (sysdir[size - 1] != '\\' ? "\\cmd.exe" : "cmd.exe"); 
    args.push_back("cmd"); 
    args.push_back("/c"); 
    args.push_back(command); 
#endif
ar7v8xwq

ar7v8xwq1#

在boost.process0.5下引入了x1m0 n1 API,所以下面的代码可能会让您有所了解

#if defined(BOOST_POSIX_API) 
    #define SHELL_COMMAND_PREFIX "-c"
#elif defined(BOOST_WINDOWS_API) 
    #define SHELL_COMMAND_PREFIX "/c"
#endif

filesystem::path shellPath = process::shell_path();
std::string cl = shell_path().string() + " " SHELL_COMMAND_PREFIX " ";
cl += "ping 127.0.0.1";
execute(  
        set_cmd_line(cl),
        throw_on_error()
);

如果您真的想隐藏#ifdef,我会继续编辑boost源代码,以返回相关的命令前缀(添加新的API),毕竟它是开源的,不是吗?:)。您可以在boost/process/windows/shell_path.hpp和boost/process/posix/shell_path.hpp中找到要编辑的相关源代码

相关问题