如何使用C ++ libboost运行进程并获取其输出? [英] How to run a process and get its output using c++ libboost?
本文介绍了如何使用C ++ libboost运行进程并获取其输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试运行外部Shell命令并使用C ++的Boost库读取其输出,但是似乎该命令未运行或者我无法访问输出.我正在使用其文档作为示例,并这样写:
I'm trying to run an external shell command and read its output using the Boost libraries for C++ but it seems that either the command is not running or I just can't access the output. I'm using their documentation as example and wrote this:
#include <boost/process.hpp>
namespace bp = boost::process;
bool is_process_running(std::string p_name){
string cmd = "ps aux 2>&1";
bp::ipstream out;
std::string line;
bp::child c(cmd, bp::std_out > out);
// the while is supposed to read each line of the output
// but the execution doesn't enter here
while(c.running() && std::getline(out, line) && !line.empty())
{
if(line.find(p_name) != std::string::npos)
{
return true;
}
}
c.wait();
return false;
}
目标是验证ps aux
的每一行输出并搜索进程是否正在运行.那么,这里可能是什么问题呢?或者,您可以为此提供一个简单的代码段吗?
The goal is to verify each line output of ps aux
and search if a process is running. So, what could be the problem here? Or, can you provide a simple snippet for doing this?
推荐答案
只需使用shell(或使用bp::system
):
Simply use a shell (or use bp::system
):
#include <boost/process.hpp>
namespace bp = boost::process;
bool is_process_running(std::string p_name){
std::vector<std::string> args { "-c", "ps aux 2>&1" };
bp::ipstream out;
bp::child c(bp::search_path("sh"), args, bp::std_out > out);
for (std::string line; c.running() && std::getline(out, line);) {
if (line.find(p_name) != std::string::npos) {
return true;
}
}
c.wait();
return false;
}
#include <iostream>
int main() {
std::cout << "bogus: " << is_process_running("bogus") << "\n";
std::cout << "a.out: " << is_process_running("a.out") << "\n";
}
打印
bogus: 0
a.out: 1
这篇关于如何使用C ++ libboost运行进程并获取其输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文