我的要求很简单:启动一个进程,等待它完成,然后捕获并处理它的输出。
最长时间以来,我一直在使用以下内容:
struct line : public std∷string {
friend std∷istream& operator>> (std∷istream &is, line &l) {
return std∷getline(is, l);
}
};
void capture(std::vector<std::string> &output, const char *command)
{
output.clear();
FILE *f = popen(command, "r");
if(f) {
__gnu_cxx::stdio_filebuf<char> fb(f, ios∷in) ;
std::istream fs(&fb);
std::istream_iterator<line> start(fs), end;
output.insert(output.end(), start, end);
pclose(f);
}
}
而且它在单线程程序上工作得很好。
但是,如果我从线程内部调用此函数,有时 popen()
调用会挂起并且永远不会返回。
因此,作为概念验证,我替换了这个丑陋的 hack 的函数:
void capture(std::vector<std::string> &output, const char *command)
{
output.clear();
std::string c = std::string(command) + " > /tmp/out.txt";
::system(c.c_str());
ifstream fs("/tmp/out.txt", std::ios::in);
output.insert(output.end(), istream_iterator<line>(fs), istream_iterator<line>());
unlink("/tmp/out.txt");
}
虽然丑陋但有效,但它让我想知道在多线程程序上捕获进程输出的正确方法是什么。
该程序在嵌入式 powerquiccII 处理器的 linux 上运行。
最佳答案
看这个:popen - locks or not thread safe?和其他引用文献似乎并不能确定 popen() 需要是线程安全的,所以也许因为您使用的是一个不太受欢迎的平台,所以您的实现不是。您是否有机会查看您平台的实现源代码?
否则,请考虑创建一个新进程并等待它。或者,嘿,坚持使用愚蠢的 system() hack,但一定要处理它的返回码!
关于c++ - 在多线程c++中捕获进程的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15110853/