正如标题所说,我想在 C++ 中的同一个 shell 进程/实例上运行 shell 命令并与其通信,我该怎么做?我查遍了每个角落,但找不到合适/直截了当的答案。我不是C++霸主,我的回答可能很愚蠢。现在我可以在unix上使用 fork/exec 的组合,但我在 Windows 上。如果有跨平台的解决方案,请在下面提及。提前致谢。
伪代码:
SHELL shell = make_shell();
shell.run("cd desktop");
shell.run("dir");
print(shell.stdout)
Run Code Online (Sandbox Code Playgroud)
C++ 中的标准库没有提供一种方法来完成您想要的操作。但是,您可以使用第三方库,例如boost::process,这将使您的程序和子进程之间的通信部分非常可移植。如果要执行内置 shell 命令或使用 shell 的命令,您仍然需要处理不同平台上使用的 shell 的差异。
该boost::process库包含许多不同的方式来创建子流程并与子流程(参考)进行通信,包括同步和异步方式,因此请浏览参考页面以了解它的功能。
这是一个简单的示例,用于在目录中boost::process::system运行命令并收集该命令的输出。它不使用shell(通常应该避免),而是用于查找命令(在您的 中)并直接执行命令,而不涉及 shell:dirdesktopboost::process::search_pathPATH
#include <boost/process.hpp>
#include <boost/process/start_dir.hpp>
#include <iostream>
#include <string>
int main() {
namespace bp = ::boost::process;
bp::ipstream out;
bp::ipstream err;
bp::system(bp::search_path("dir"),
bp::start_dir = "./desktop",
bp::std_out > out, // collect stdout in out
bp::std_err > err, // collect stderr in err
bp::std_in < stdin); // for commands reading from stdin
// display what was collected on stdout and stderr:
std::string line;
std::cout << "stdout capture:\n";
while(std::getline(out, line)) {
std::cout << '[' << line << "]\n";
}
std::cout << "\nstderr capture:\n";
while(std::getline(err, line)) {
std::cout << '[' << line << "]\n";
}
}
Run Code Online (Sandbox Code Playgroud)
注意:您需要链接boost_filesystem和boost_atomic才能使该示例正常工作。
| 归档时间: |
|
| 查看次数: |
1208 次 |
| 最近记录: |