初版。
This commit is contained in:
73
exec_cmd.cpp
Normal file
73
exec_cmd.cpp
Normal file
@@ -0,0 +1,73 @@
|
||||
#include "exec_cmd.h"
|
||||
|
||||
#include <boost/algorithm/string.hpp>
|
||||
#include <boost/asio/read.hpp>
|
||||
#include <boost/asio/read_until.hpp>
|
||||
#include <boost/asio/readable_pipe.hpp>
|
||||
#include <boost/asio/streambuf.hpp>
|
||||
#include <boost/core/ignore_unused.hpp>
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <boost/locale.hpp>
|
||||
#include <boost/process.hpp>
|
||||
#include <boost/process/start_dir.hpp>
|
||||
#include <boost/system/error_code.hpp>
|
||||
#include <fmt/format.h>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
namespace proc = boost::process;
|
||||
namespace asio = boost::asio;
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
ExecCMD::ExecCMD()
|
||||
{
|
||||
}
|
||||
|
||||
int ExecCMD::ExecuteCmd(const std::string& exe, std::vector<std::string>& args, const std::string& workDir)
|
||||
{
|
||||
// std::vector<std::string> args = {"/c", "call", vsBat, "&&", "set"};
|
||||
asio::io_context ctx;
|
||||
try {
|
||||
//
|
||||
asio::readable_pipe rp{ctx};
|
||||
proc::process c{ctx, exe, args, proc::process_stdio{{}, rp, {}}, boost::process::process_start_dir(workDir)};
|
||||
|
||||
std::string line;
|
||||
boost::system::error_code ec;
|
||||
asio::streambuf buffer;
|
||||
|
||||
while (true) {
|
||||
asio::read_until(rp, buffer, '\n', ec);
|
||||
if (!ec) {
|
||||
std::istream is(&buffer);
|
||||
std::getline(is, line);
|
||||
std::cout << line << "\n";
|
||||
continue;
|
||||
}
|
||||
if (ec == asio::error::eof) {
|
||||
std::istream is(&buffer);
|
||||
std::getline(is, line);
|
||||
std::cout << line << "\n";
|
||||
break;
|
||||
} else {
|
||||
#if defined(_WIN32)
|
||||
std::cerr << boost::locale::conv::between(ec.message(), "UTF-8", "GBK") << std::endl;
|
||||
#else
|
||||
std::cerr << ec.message() << std::endl;
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
}
|
||||
c.wait();
|
||||
int exit_code = c.exit_code();
|
||||
return exit_code;
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
#if defined(_WIN32)
|
||||
std::cerr << "异常: " << boost::locale::conv::between(e.what(), "UTF-8", "GBK") << std::endl;
|
||||
#else
|
||||
std::cerr << e.what() << std::endl;
|
||||
#endif
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user