我的要求很简单:启动一个过程,等待它完成,然后捕获并处理它的输出.
My requirements are simple: start a process, wait for it to finish, then capture and process it's output.
最长时间以来,我一直在使用以下内容:
For the longest time I've been using the following:
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); } }它在单线程程序上非常有效.
And it works really well on single threaded programs.
但是,如果我从线程内部调用此函数,有时 popen()调用会挂起并且永远不会返回.
However, if I call this function from inside a thread, sometimes the popen() call hangs and never return.
因此,作为概念验证,我替换了此丑陋的功能:
So, as a proof-of-concept I replaced the function for this ugly 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"); }这很丑陋,但是可行,但是让我一直想知道在多线程程序上捕获进程输出的正确方法是什么.
It's ugly but works, however it kept me wondering what would be the proper way to capture a process output on a multi-threaded program.
该程序在嵌入式powerquiccII处理器中的linux上运行.
The program runs on linux in a embedded powerquiccII processor.
推荐答案请参见:popen-锁定还是线程安全?和其他引用似乎并不能确定popen()是否需要线程安全,所以也许由于您使用的是不那么受欢迎的平台,所以实现不是.您有机会查看自己平台的实现源代码吗?
See this: popen - locks or not thread safe? and other references do not seem conclusive that popen() needs to be thread-safe, so perhaps since you are using a less-popular platform, your implementation is not. Any chance you can view the source code of the implementation for your platform?
否则,请考虑创建一个新进程并等待它.还是嘿,坚持使用愚蠢的system()骇客,但要处理其返回码!
Otherwise, consider creating a new process and waiting upon it. Or hey, stick with the silly system() hack, but do handle its return code!
更多推荐
在多线程C ++中捕获进程的输出
发布评论