如何使用 boost::p rocess::child 处理路径中的空格

How to deal with spaces in path using boost::process::child?

本文关键字:路径 空格 处理 rocess 何使用 boost child      更新时间:2023-10-16

我需要执行一个Windows Batch脚本。根据公司政策,我必须使用boost::process::child。Windows 批处理脚本的路径包含空格(例如 C:Foo Barbatch.bat (。

我正在使用以下代码:

namespace bp = boost::process;
error_code errorCode;
bp::ipstream errorStream;
auto child = bp::child("C:\Foo Bar\batch.bat",
    errorCode,
    bp::std_out > bp::null,    // ignore standard output
    bp::std_err > errorStream, // capture standard error
    bp::windows::hide,        // hide window
    bp::shell);               // use shell
  vector<string> errorData;
  string errorLine;
  while (child.running() && getline(errorStream, errorLine) && !errorLine.empty())
  {
    errorData.push_back(errorLine);
  }
  child.wait();

问题是系统(boost::p rocess(找不到路径。错误消息如下所示:

"C:\Foo"不被识别为内部或外部命令、可操作程序或批处理文件。

我还尝试了以下掩蔽变体:

  • C:\Foo Bar\batch.bat
  • C:\Foo Bar\batch.bat
  • "C:\Foo Bar\batch.bat"
  • C:\Foo~1\batch.bat

如何正确屏蔽空格,以便child()正确查找/执行批处理脚本?

"C:\Foo Bar\batch.bat"包装成 boost::filesystem::path() ,以便它为您引用字符串:

auto child = bp::child(boost::filesystem::path("C:\Foo Bar\batch.bat"),

我建议遵循@Maxim的答案。

或者,使用反斜杠转义空格:

"C:\Foo\ Bar\batch.bat"
bp::child c(
    bp::exe(boost::filesystem::path("C:\Foo Bar\batch.bat").c_str()),
    bp::cmd("options here"), 
    bp::environment(env),       
    bp::std_in.close(),
    bp::std_out > os,
    bp::std_err > es,
    bp::start_dir("workdir here")
);

假设这变成了 Windows CreateProcess 调用,那么应用程序的路径必须用双引号引起来,以便在路径中允许空格。事实上,建议路径始终用双引号括起来。

因此,您将使用:

auto child = bp::child(""C:\Foo Bar\batch.bat"",

我不知道 Boost::child 是否真的会允许它工作。