在多线程C ++中捕获进程的输出

编程入门 行业动态 更新时间:2024-10-26 08:20:51
本文介绍了在多线程C ++中捕获进程的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的要求很简单:启动一个过程,等待它完成,然后捕获并处理它的输出.

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 ++中捕获进程的输出

本文发布于:2023-08-05 05:40:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1303010.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多线程   进程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!