我如何使用C捕捉另一个进程的输出? [英] How can I capture another process's output using C?

查看:155
本文介绍了我如何使用C捕捉另一个进程的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用纯C我捕捉另一个进程的输出?你能否提供样品code?

How can I capture another process's output using pure C? Can you provide sample code?

编辑:让我们假设Linux系统。我会很感兴趣的是pretty便携code。所有我想要做的就是执行命令,捕捉它的输出,并以某种方式处理它。

let's assume Linux. I would be interested in "pretty portable" code. All I want to do is to execute a command, capture it's output and process it in some way.

推荐答案

有几种选择,但它确实有点取决于你的平台上。这就是说的popen 在大多数地方工作,例如

There are several options, but it does somewhat depend on your platform. That said popen should work in most places, e.g.

#include <stdio.h>

FILE *stream;
stream = popen("acommand", "r");

/* use fread, fgets, etc. on stream */

pclose(stream);

请注意,这有一个非常具体的使用,运行命令 acommand 创建过程,并重视其标准出了诸如方式,使其从访问通过流程序 FILE *

Note that this has a very specific use, it creates the process by running the command acommand and attaches its standard out in a such as way as to make it accessible from your program through the stream FILE*.

如果您需要连接到现有的过程中,或者需要做更丰富的业务,你可能需要考虑其他的设施。 Unix有钩住了处理的各种机制,标准输出等。

If you need to connect to an existing process, or need to do richer operations, you may need to look into other facilities. Unix has various mechanisms for hooking up a processes stdout etc.

在windows下,你可以使用的CreateProcess API来创建一个新的流程和挂钩它的标准输出句柄,你想要什么。 Windows还支持的popen

Under windows you can use the CreateProcess API to create a new process and hook up its standard output handle to what you want. Windows also supports popen.

有没有纯C的方式做到这一点,我知道了,所以它总是会有点依赖于特定平台的API。

There's no plain C way to do this that I know of though, so it's always going somewhat dependent on platform specific APis.

的popen 似乎理想的,它是pretty便携,我不认为有一个类似Unix的操作系统没有它,的确是单一Unix规范的一部分,和 POSIX ,它可以让你做你想要什么,执行过程中,抓住它的输出和处理它。

Based on your edits popen seems ideal, it is "pretty portable", I don't think there's a unix like OS without it, indeed it is part of the Single Unix Specification, and POSIX, and it lets you do exactly what you want, execute a process, grab its output and process it.

这篇关于我如何使用C捕捉另一个进程的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆