2012-10-07 2 views
3

나는 새롭게 Boost.Process 0.5이 나오지만 Windows Linux 및 Mac에서 ping 또는 echo을 실행하는 방법을 알지 못합니다. 창에Boost.Process 0.5로 명령 줄/터미널 유틸리티를 실행하는 방법은 무엇입니까?

#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에서 leaast에서 일하고있어? (나는 어리 석고 어떤 유닉스 터미널 (또는 Linux Bash와 mac default one을 위해) 적어도 하나의 경로를 쓰는 방법을 모른다.) 그래서 Windows와 Unix에서 Boost.Process 0.5와 함께 commandline/terminal utils를 실행하는 법 (매번 터미널에 경로를 쓰는 것이 아니라 echo 또는 ping과 같은 인수를 작성하는 것과 같은 좋은 방법)?

... prevoius 버전 안에서 발견 관련 코드는 : 당신이 정말로 원하는 경우 boost.process 0.5 그래서 도입 된 shell_path() API에서

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 

답변

1

는 다음 최대

#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를 숨기려면 부스트 소스를 편집하여 관련 명령 접두어 (새 API 추가)를 반환하고, 오픈 소스는 결국 그렇지 않습니까? :). boost/process/windows/shell_path.hpp 및 boost/process/posix/shell_path.hpp에서 편집 할 관련 소스를 찾을 수 있습니다.

관련 문제